package com.xayy.health.mgt.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.Method;
import cn.kawins.base.result.ResultEnum;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.base.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xayy.health.core.config.param.AlgorithmParam;
import com.xayy.health.core.config.param.DsParam;
import com.xayy.health.core.constant.HealthManagerConstant;
import com.xayy.health.core.constant.TableNameConstant;
import com.xayy.health.core.enums.MultiParameterEnum;
import com.xayy.health.core.exception.HealthException;
import com.xayy.health.core.utils.ListUtil;
import com.xayy.health.mgt.mapper.DiagnoseMultipleParametersDataMapper;
import com.xayy.health.mgt.mapper.FaultInfoMapper;
import com.xayy.health.mgt.mapper.SelectTelemetryDataSourceMapper;
import com.xayy.health.mgt.model.*;
import com.xayy.health.mgt.model.dto.AlgorithmParseDTO;
import com.xayy.health.mgt.model.dto.MultiparatersDTO;
import com.xayy.health.mgt.model.dto.SlopeAlgorithmParseDTO;
import com.xayy.health.mgt.model.dto.TelemetryDto;
import com.xayy.health.mgt.model.vo.ThresholdJudgmentAlgorithmVo;
import com.xayy.health.mgt.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxa
 * @description 事后诊断多参数
 */

@Service
@Slf4j
public class MultiParameterServiceImpl implements MultiParameterService {

    @Autowired
    DiagnoseService diagnoseService;
    @Autowired
    private DataQualityService dataQualityService;
    @Autowired
    private SatelliteCodeService satelliteCodeService;
    @Autowired
    private AlgorithmParam algorithmParam;
    @Autowired
    private FaultInfoMapper faultInfoMapper;
    @Autowired
    private DsParam dsParam;
    @Autowired
    private TaskChildInfoService taskChildInfoService;

    @Autowired
    private TaskInfoService taskInfoService;

    @Autowired
    private DiagnoseMultipleParametersDataMapper diagnoseMultipleParametersDataMapper;

    @Autowired
    private SelectTelemetryDataSourceMapper selectTelemetryDataSourceMapper;

    /**
     * 事后诊断多参数试算
     *
     * @param modelTrain 入参信息
     * @return 结果日志
     */
    @Override
    public Object multiparameter(ModelTrain modelTrain) {
        Map<String, Object> args = new LinkedHashMap<>();
        List<Map<String, Object>> telemetryList = new ArrayList<>();
        List<String> paramCodeList = modelTrain.getParamCodes();
        List<String> paramCodes = paramCodeList.stream().sorted().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(paramCodes)) {
            for (String paramCode : paramCodes) {
                // 查询遥测数据
                TelemetryDto telemetryDto = new TelemetryDto();
                telemetryDto.setSatelliteCode(modelTrain.getSatelliteCode());
                telemetryDto.setParamCodes(new String[]{paramCode});
                telemetryDto.setStartTime(modelTrain.getStartTime());
                telemetryDto.setEndTime(modelTrain.getEndTime());
                Map<String, List<TelemetryData>> map = diagnoseService.selectTelemetryData(telemetryDto);
                List<TelemetryData> ycList = map.get(paramCode);
                if(!CollectionUtils.isEmpty(ycList)){
                    for(TelemetryData data:ycList){
                         if(StringUtils.isEmpty(data.getValue())){
                            throw new HealthException("参数"+paramCode+"遥测数据中存在空值......");
                         }
                    }
                    List<ArrayList<String>> collect = ycList.stream().map(x -> CollUtil.newArrayList(x.getTime(), x.getValue())).collect(Collectors.toList());
                    args.put(paramCode, ycList);
                    Map<String, Object> telemetry = new LinkedHashMap<>();
                    telemetry.put("name", paramCode);
                    telemetry.put("data", collect);
                    telemetryList.add(telemetry);
                }

            }
        }
        return curveSlopeAnalysis(args, telemetryList, modelTrain);
    }

    /**
     * 计算数据是否异常 计算方法：曲线斜率分析
     */
    private Map<String, Object> curveSlopeAnalysis(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain) {
        /*算法名称*/
        String multiparameterAlgName = modelTrain.getMultiparameterAlgName();

        if (multiparameterAlgName.equals(MultiParameterEnum.SLOPEALGORITHM.getCode())) {
            //斜率异常检查
            return slopeAlgorithm(args, telemetryList);
        } else if (multiparameterAlgName.equals(MultiParameterEnum.MEANFEATUREALGORITHM.getCode())) {
            //均值特征
            return meanFeatureAlgorithm(args, telemetryList, modelTrain);
        } else if (multiparameterAlgName.equals(MultiParameterEnum.KNEARESTNEIGHBORALGORITHM.getCode())) {
            //k近邻
            return kNearestNeighborAlgorithm(args, telemetryList, modelTrain);
        } else if (multiparameterAlgName.equals(MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode())) {
            //双参数诊断
            return twoParameterDiagnosisAlgorithm(args, telemetryList, modelTrain);
        } else if (multiparameterAlgName.equals(MultiParameterEnum.THRESHOLDJUDGMENTALGORITHM.getCode())) {
            //门限值判断算法
            return thresholdJudgmentAlgorithm(args, telemetryList, modelTrain);
        }
        return new HashMap<>(2);
    }

    /**
     * 斜率异常检查
     *
     * @param args          入参
     * @param telemetryList 遥测入参
     * @return Map<String, Object>
     */
    public Map<String, Object> slopeAlgorithm(Map<String, Object> args, List<Map<String, Object>> telemetryList) {

        HttpResponse postResponse = null;
        JSONArray jsonArrays = null;
        try {
            postResponse = HttpUtil.createRequest(Method.POST, algorithmParam.getSlopeAlgorithm()).body(JSON.toJSONString(args)).execute();
            /*返回结果*/
            if (postResponse.getStatus() != HttpStatus.HTTP_OK) {
                // 返回为空默认为解析失败
                throw new HealthException("算法调用失败");
            }
            jsonArrays = JSONArray.parseArray(postResponse.body());
        } catch (Exception e) {
            JSONObject map1 = JSONObject.parseObject(postResponse.body(), JSONObject.class);
            if (ResultEnum.FAIL.getCode().equals(map1.getInteger(HealthManagerConstant.STATUS_CODE))) {
                throw new HealthException(map1.getString("msg"));
            }
        }
        ArrayList<Object> list = new ArrayList<>();
        /*Y轴数据包*/
        List<Map<String, Object>> seriesList = new ArrayList<>();
        /*参数集合*/
        List<String> legendData = new ArrayList<>();
        /*斜率集合*/
        Map<String, Double> gradientMap = new LinkedHashMap<>();
        /*X轴数据*/
        Set<Object> xAxis = new LinkedHashSet<>();
        String maxName = null;
        Double maxGradient = null;
        int i = 1;
        String timeIndex = "";
        for (Object obj : jsonArrays) {
            JSONObject valObj = JSONObject.parseObject(obj.toString());
            /*参数*/
            String name = valObj.getString("name");
            legendData.add(name);
            /*斜率*/
            String gradient = valObj.getString("gradient");
            if (maxGradient == null) {
                maxName = name;
                maxGradient = Double.parseDouble(gradient);
                timeIndex = valObj.getString("time_index");
            } else {
                if (0 > Double.compare(Math.abs(maxGradient), Math.abs(Double.parseDouble(gradient)))) {
                    maxGradient = Double.parseDouble(gradient);
                    maxName = name;
                    timeIndex = valObj.getString("time_index");
                }
            }
            gradientMap.put(name, new BigDecimal(gradient).setScale(6,RoundingMode.HALF_DOWN).doubleValue());
            /*时间点数据*/
            Map<String, Object> seriesMap = new LinkedHashMap<>();
            seriesMap.put("name", name);
            seriesMap.put("type", "line");
            /*数据*/
            String value1 = valObj.getString("value");
            JSONArray jsonArray = JSONArray.parseArray(value1);

            //遥测数据长度和算法返回的长度保持一致
            HashMap<String, Object> repeatAssembleTelemetryList = new HashMap<>(2);
            if (CollUtil.isNotEmpty(jsonArray)) {
                int size = jsonArray.size();
                for (Map<String, Object> map : telemetryList) {
                    if (map.get("name").equals(name)) {
                        List<ArrayList> telemetryListByName = (List<ArrayList>) map.get("data");
                        if (size != telemetryListByName.size()) {
                            List<ArrayList> telemetryData = telemetryListByName.stream().limit(size).collect(Collectors.toList());
                            if (i == 1) {
                                for (ArrayList arrayList : telemetryData) {
                                    xAxis.add(arrayList.get(0));
                                }
                            }
                            i++;
                            repeatAssembleTelemetryList.put("data", telemetryData);
                            repeatAssembleTelemetryList.put("name", name);
                            list.add(repeatAssembleTelemetryList);
                        }
                    }
                }
            }
            /*Y轴数据*/
            List<Double> series = new ArrayList<>();
            for (Object str : jsonArray) {
                JSONObject valuesAttr = JSONObject.parseObject(str.toString());
                String y = valuesAttr.getString("y");
                series.add(Double.parseDouble(y));
            }

            seriesMap.put("data", series);
            seriesList.add(seriesMap);
        }

        String data = null;
        //处理最大曲线斜率
        if(!CollectionUtils.isEmpty(gradientMap)){
            List<Map.Entry<String,Double>> gradientList=new ArrayList<>(gradientMap.entrySet());
            Collections.sort(gradientList,(o1,o2)->Double.compare(o1.getValue(), o2.getValue()));
            if(Double.compare(gradientList.get(0).getValue(),gradientList.get(list.size()-1).getValue())!=0){
                maxName=gradientList.get(list.size()-1).getKey();
                data = "参数" + maxName + "的斜率值较大";
            }
        }
        return MapUtil.builder(new HashMap<String, Object>(8)).put("timeIndex", timeIndex).put("xAxis", xAxis).put("series", seriesList).put("legend", legendData).put("gradientMap", gradientMap).put("calResult", "").put("telemetryList", list).put("msg", data).build();
    }

    /**
     * 均值特征
     *
     * @param args          遥测
     * @param telemetryList 遥测
     * @param modelTrain    入参
     * @return Map<String, Object>
     */
    public Map<String, Object> meanFeatureAlgorithm(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain) {
        modelTrain.setTelemetryDataList(args);
        HttpResponse postResponse = HttpUtil.createRequest(Method.POST, algorithmParam.getMeanFeatureAlgorithm()).body(JSON.toJSONString(modelTrain)).execute();
        JSONArray jsonArrays = executionExceptionData(args, telemetryList, modelTrain, postResponse);


        JSONObject algorithmParseObject = jsonArrays.getObject(0, JSONObject.class);
        Map<String, Object> parseObjectMap = parseAnomalyAndValueData(algorithmParseObject);
        //异常提示
        String data = (String) parseObjectMap.get("data");
        //参数
        ArrayList<String> paramList = (ArrayList<String>) parseObjectMap.get("paramList");
        //右侧
        JSONArray value = (JSONArray) parseObjectMap.get("value");

        JSONObject graphObject = algorithmParseObject.getObject("graph", JSONObject.class);

        Set<String> graphKeySetList = graphObject.keySet().stream().sorted(Comparator.comparing(String::toString)).collect(Collectors.toCollection(LinkedHashSet::new));

        ArrayList<Object> seriesList = new ArrayList<>();
        Set<String> xAxis = new LinkedHashSet<>();
        for (String key : graphKeySetList) {
            HashMap<String, Object> seriesMap = new HashMap<>(6);
            seriesMap.put("name", key);
            seriesMap.put("type", "line");
            JSONArray graphObj = JSONObject.parseObject(JSON.toJSONString(graphObject.get(key)), JSONArray.class);
            ArrayList<Double> series = new ArrayList<>();
            if ("threshold".equals(key)) {
                seriesMap.put("name", "均值中位数");
                for (Object o1 : graphObj) {
                    JSONArray parseObject = JSONObject.parseObject(JSON.toJSONString(o1), JSONArray.class);
                    for (Object o2 : parseObject) {
                        JSONObject object = JSONObject.parseObject(JSON.toJSONString(o2), JSONObject.class);
                        String x = object.getString("time");
                        xAxis.add(x);
                        String y = object.getString("value");
                        series.add(Double.parseDouble(y));
                    }
                    seriesMap.put("data", series);
                }
            } else {
                for (Object o1 : graphObj) {
                    JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(o1), JSONObject.class);
                    String x = parseObject.getString("time");
                    xAxis.add(x);
                    String y = parseObject.getString("value");
                    series.add(Double.parseDouble(y));
                }
                seriesMap.put("data", series);
            }
            seriesList.add(seriesMap);
        }

        List<String> paramCodes = modelTrain.getParamCodes();
        Set<String> xLineAxis = new LinkedHashSet<>();
        if (CollUtil.isNotEmpty(paramCodes)) {
            for (Map<String, Object> map : telemetryList) {
                List list = (List) map.get("data");
                for (Object o : list) {
                    List list1 = (List) o;
                    String o1 = (String) list1.get(0);
                    xLineAxis.add(o1);
                }
            }
        }
        //下面图遥测横坐标
        return MapUtil.builder(new HashMap<String, Object>(9)).put("xLineAxis", xLineAxis)
                //上面图横坐标
                .put("xAxis", xAxis)
                .put("downxAxis", xAxis)
                //上面折线图数据
                .put("series", seriesList)
                //参数
                .put("legend", paramList)
                //右侧数据
                .put("gradientMap", value)
                //没啥用
                .put("calResult", "")
                //遥测数据
                .put("telemetryList", telemetryList)
                .put("msg", algorithmParseObject.getString("msg"))
                .put("data", data).build();

    }


    /**
     * k邻近
     *
     * @param args          遥测
     * @param telemetryList 遥测
     * @param modelTrain    入参
     * @return Map<String, Object>
     */
    public Map<String, Object> kNearestNeighborAlgorithm(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain) {
        HttpResponse postResponse = HttpUtil.createRequest(Method.POST, algorithmParam.getKNearestNeighborAlgorithm()).body(JSON.toJSONString(args)).execute();
        JSONArray jsonArrays = executionExceptionData(args, telemetryList, modelTrain, postResponse);
        JSONObject algorithmParseObject = jsonArrays.getObject(0, JSONObject.class);
        Map<String, Object> parseObjectMap = parseAnomalyAndValueData(algorithmParseObject);
        String data = (String) parseObjectMap.get("data");
        ArrayList<String> paramList = (ArrayList<String>) parseObjectMap.get("paramList");
        JSONArray value = (JSONArray) parseObjectMap.get("value");
        HashMap<Object, ArrayList<ArrayList<Object>>> graphMap = new HashMap<>(6);

        //散点
        JSONObject graphList = algorithmParseObject.getObject("graph", JSONObject.class);

        int i = 1;
        Set<Object> xAxis = new LinkedHashSet<>();
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        if (CollUtil.isNotEmpty(telemetryList)) {
            for (Map<String, Object> map : telemetryList) {
                for (String param : paramList) {
                    if (param.equals(map.get("name"))) {
                        HashMap<String, Object> repeatAssembleList = new HashMap<>(2);
                        List<ArrayList> dataList = (List<ArrayList>) map.get("data");
                        List<ArrayList> telemetryData = dataList.stream().limit(graphList.getJSONArray(param).size()).collect(Collectors.toList());
                        if (i == 1) {
                            for (ArrayList teleData : telemetryData) {
                                xAxis.add(teleData.get(0));
                            }
                        }
                        i++;
                        repeatAssembleList.put("name", param);
                        repeatAssembleList.put("data", telemetryData);
                        arrayList.add(repeatAssembleList);
                    }
                }
            }
        }


        //k邻近提示对比语句
        StringBuilder builder = new StringBuilder();
        if (CollUtil.isNotEmpty(value)) {
            BigDecimal sum = new BigDecimal(0);
            BigDecimal average = new BigDecimal(0);
            ArrayList<BigDecimal> doubleArrayList = new ArrayList<>();
            for (Object dto : value) {
                //TODO: 集合必须制定泛型
                Map map = JSON.parseObject(dto.toString(), Map.class);
                BigDecimal value1 = (BigDecimal) map.get("value");
                doubleArrayList.add(value1);
            }
            for (int j = 0; j <= doubleArrayList.size() - 1; j++) {
                sum = doubleArrayList.get(j).add(sum);
            }
            ArrayList<Object> tipsList = new ArrayList<>();
            average = (sum.divide(new BigDecimal(doubleArrayList.size()), 3, RoundingMode.HALF_UP)).multiply(new BigDecimal(2));
            for (Object dto : value) {
                Map map = JSON.parseObject(dto.toString(), Map.class);
                BigDecimal value1 = (BigDecimal) map.get("value");
                if (value1.compareTo(average) > 0) {
                    tipsList.add(map.get("time"));
                }
            }
            if (CollUtil.isNotEmpty(tipsList)) {
                builder.append(tipsList.toString().replace("[", "").replace("]", "") + "大于2倍邻近距离均值");
            }
        }

        Set<String> keySet = graphList.keySet();
        for (String key : keySet) {
            Object o = graphList.get(key);
            List graphObj = (List) o;
            ArrayList<ArrayList<Object>> xygraphList = new ArrayList<>();
            for (Object o1 : graphObj) {
                JSONObject graphMap1 = (JSONObject) o1;
                String graphTime = graphMap1.getString("time");
                Double graphvalue = graphMap1.getDouble("value");
                ArrayList<Object> list = new ArrayList<>();
                list.add(graphTime);
                list.add(graphvalue);
                xygraphList.add(list);
            }
            graphMap.put(key, xygraphList);
        }
        //x轴
        return MapUtil.builder(new HashMap<String, Object>(8)).put("xAxis", xAxis)
                //散点图数据
                .put("graphMap", graphMap)
                //参数代号
                .put("legend", paramList)
                .put("downxAxis", xAxis)
                //右侧数据
                .put("gradientMap", value)
                //异常提示语句
                .put("data", data)
                //遥测数据
                .put("telemetryList", arrayList)
                .put("msg", algorithmParseObject.getString("msg"))
                .put("tips", builder).build();
    }

    /**
     * 双参数
     *
     * @param args          遥测
     * @param telemetryList 遥测
     * @param modelTrain    入参
     * @return Map<String, Object>
     */
    //TODO: 1.此方法太长, 业务耦合过高,无法维护和修改,需重构;2.方法名没按照驼峰要求命名
    public Map<String, Object> twoParameterDiagnosisAlgorithm(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain) {
        if (modelTrain.getParamCodes().size() < 2) {
            throw new HealthException("请选择两组参数");
        }

        List<String> paramCodeList = modelTrain.getParamCodes();
        String[] paramArray = paramCodeList.toArray(new String[0]);
        TelemetryDto telemetryDto = new TelemetryDto()
                .setSatelliteCode(modelTrain.getSatelliteCode())
                .setStartTime(modelTrain.getNormalStartTime())
                .setEndTime(modelTrain.getNormalEndTime())
                .setParamCodes(paramArray);
        Map<String, List<TelemetryData>> listMap = diagnoseService.selectTelemetryData(telemetryDto);
        modelTrain.setNormalTimeTelemetryDataList(listMap);
        modelTrain.setTelemetryDataList(args);
        if (Boolean.TRUE.equals(dsParam.getTwoParameterAddEightHour())) {
            modelTrain.setNormalStartTime(DateUtil.offsetHour(modelTrain.getNormalStartTime(), 8));
            modelTrain.setNormalEndTime(DateUtil.offsetHour(modelTrain.getNormalEndTime(), 8));
        }
        HttpResponse postResponse = HttpUtil.createRequest(Method.POST, algorithmParam.getTwoParameterDiagnosisAlgorithm()).body(JSON.toJSONString(modelTrain)).execute();
        JSONArray jsonArrays = executionExceptionData(args, telemetryList, modelTrain, postResponse);
        JSONObject algorithmParseObject = jsonArrays.getObject(0, JSONObject.class);
        List<String> codes = modelTrain.getParamCodes();
        String[] split = codes.stream().toArray(String[]::new);
        ArrayList<Object> normalLineList = new ArrayList<>();
        ArrayList<Object> detectLineList = new ArrayList<>();

        int i = 1;
        for (String code : codes) {
            Set<String> keySet = algorithmParseObject.keySet();
            for (String key : keySet) {
                HashMap<String, Object> detectGraphMap = new HashMap<>(3);
                HashMap<String, Object> normalGraphMap = new HashMap<>(3);
                if (key.equals(code + "_detect")) {
                    detectGraphMap.put("name", code + "诊断");
                    detectGraphMap.put("type", "line");
                    List o = (List) algorithmParseObject.get(key);

                    ArrayList<Object> list = new ArrayList<>();
                    for (Object object : o) {
                        ArrayList<Object> xyTimeValue = new ArrayList<>();
                        JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(object));
                        xyTimeValue.add(parseObject.get("time"));
                        xyTimeValue.add(parseObject.get("value"));
                        list.add(xyTimeValue);
                    }
                    detectGraphMap.put("data", list);
                    detectLineList.add(detectGraphMap);

                } else if (key.equals(code + "_normal")) {
                    normalGraphMap.put("name", code + "诊断");
                    normalGraphMap.put("type", "line");
                    List o = (List) algorithmParseObject.get(key);
                    ArrayList<Object> normalList = new ArrayList<>();
                    for (Object object : o) {
                        ArrayList<Object> xyTimeValue = new ArrayList<>();
                        JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(object));
                        xyTimeValue.add(parseObject.get("time"));
                        xyTimeValue.add(parseObject.get("value"));
                        normalList.add(xyTimeValue);
                    }
                    normalGraphMap.put("data", normalList);
                    normalLineList.add(normalGraphMap);
                } else if ("scatter".equals(key) && i == 1) {
                    i++;
                    detectGraphMap.put("name", "散点");
                    detectGraphMap.put("chartType", "scatter");
                    List o = (List) algorithmParseObject.get(key);
                    ArrayList<Object> scatterList = new ArrayList<>();
                    for (Object object : o) {
                        ArrayList<Object> objectArrayList = new ArrayList<>();
                        JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(object));
                        objectArrayList.add(parseObject.get("time"));
                        objectArrayList.add(parseObject.get("value"));
                        scatterList.add(objectArrayList);
                    }
                    detectGraphMap.put("data", scatterList);
                    detectLineList.add(detectGraphMap);
                }
            }
        }
        List<HashMap<String, DateTime>> dateTimeList = new ArrayList<>();
        String detectAxisStr = algorithmParseObject.get("detect_axis").toString();
        ArrayList<String> detectAxis = new ArrayList<>();
        if (StrUtil.isNotEmpty(detectAxisStr)) {
            List detectList = (List) algorithmParseObject.get(detectAxisStr);
            if (CollUtil.isNotEmpty(detectList)) {
                for (Object detectData : detectList) {
                    JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(detectData));
                    detectAxis.add(parseObject.getString("time"));
                }
                detectAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                HashMap<String, DateTime> detectTimeMap = new HashMap<>(2);
                String detectStartTimeStr = detectAxis.get(0);
                if (detectStartTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                    detectStartTimeStr.substring(0, detectStartTimeStr.length() - 4);
                }
                DateTime detectStartTime = DateUtil.parse(detectStartTimeStr, "yyyy-MM-dd HH:mm:ss");
                String detectEndTimeStr = detectAxis.get(detectAxis.size() - 1);
                if (detectEndTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                    detectEndTimeStr.substring(0, detectStartTimeStr.length() - 4);
                }
                DateTime detectEndTime = DateUtil.parse(detectEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                detectTimeMap.put("detectStartTime", detectStartTime);
                detectTimeMap.put("detectEndTime", detectEndTime);
                dateTimeList.add(detectTimeMap);
            }
        }


        String normalAxisStr = algorithmParseObject.get("normal_axis").toString();
        ArrayList<String> normalAxis = new ArrayList<>();
        if (StrUtil.isNotEmpty(normalAxisStr)) {
            List normalList = (List) algorithmParseObject.get(normalAxisStr);
            if (CollUtil.isNotEmpty(normalList)) {
                for (Object normalData : normalList) {
                    JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(normalData));
                    normalAxis.add(parseObject.getString("time"));
                }
                normalAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                HashMap<String, DateTime> normalTimeMap = new HashMap<>(2);
                String normalStartTimeStr = normalAxis.get(0);
                if (normalStartTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                    normalStartTimeStr.substring(0, normalStartTimeStr.length() - 4);
                }
                DateTime normalStartTime = DateUtil.parse(normalStartTimeStr, "yyyy-MM-dd HH:mm:ss");
                String normalEndTimeStr = normalAxis.get(normalAxis.size() - 1);
                if (normalEndTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                    normalEndTimeStr.substring(0, normalEndTimeStr.length() - 4);
                }
                DateTime normalEndTime = DateUtil.parse(normalEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                normalTimeMap.put("normalStartTime", normalStartTime);
                normalTimeMap.put("normalEndTime", normalEndTime);
                dateTimeList.add(normalTimeMap);
            }
        }

        List<Map<String, Object>> normalTelemetryList = new ArrayList<>();
        List<Map<String, Object>> detectTelemetryList = new ArrayList<>();
        if (CollUtil.isNotEmpty(modelTrain.getParamCodes()) && CollUtil.isNotEmpty(dateTimeList)) {
            for (HashMap<String, DateTime> map : dateTimeList) {
                for (String paramCode : modelTrain.getParamCodes()) {
                    // 查询遥测数据
                    TelemetryDto telemetryDto1 = new TelemetryDto();
                    telemetryDto1.setSatelliteCode(modelTrain.getSatelliteCode());
                    telemetryDto1.setParamCodes(new String[]{paramCode});
                    if (map.containsKey("detectStartTime") && map.containsKey("detectEndTime")) {
                        telemetryDto1.setStartTime(map.get("detectStartTime"));
                        telemetryDto1.setEndTime(map.get("detectEndTime"));
                    } else {
                        telemetryDto1.setStartTime(map.get("normalStartTime"));
                        telemetryDto1.setEndTime(map.get("normalEndTime"));
                    }
                    Map<String, List<TelemetryData>> map1 = diagnoseService.selectTelemetryData(telemetryDto1);
                    List<TelemetryData> ycList = map1.get(paramCode);
                    List<ArrayList<String>> collect = ycList.stream().map(x -> CollUtil.newArrayList(x.getTime(), x.getValue())).collect(Collectors.toList());
                    Map<String, Object> telemetry = new LinkedHashMap<>();
                    telemetry.put("name", paramCode + "正常");
                    telemetry.put("data", collect);
                    if (map.containsKey("detectStartTime") && map.containsKey("detectEndTime")) {
                        detectTelemetryList.add(telemetry);
                    } else {
                        normalTelemetryList.add(telemetry);
                    }

                }

            }
        }

        List<String> detectTelemetryAxis = new ArrayList<>();
        List detectTelemetryArrayList = (List) detectTelemetryList.get(0).get("data");
        if (CollUtil.isNotEmpty(detectTelemetryArrayList)) {
            for (Object o : detectTelemetryArrayList) {
                List list1 = (List) o;
                String o1 = (String) list1.get(0);
                detectTelemetryAxis.add(o1);
            }
            detectTelemetryAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
        }

        List<String> normalTelemetryAxis = new ArrayList<>();
        if (CollUtil.isNotEmpty(detectTelemetryArrayList)) {
            List normalTelemetryArrayList = (List) normalTelemetryList.get(0).get("data");
            for (Object o1 : normalTelemetryArrayList) {
                List oList = (List) o1;
                String timeStr = (String) oList.get(0);
                normalTelemetryAxis.add(timeStr);
            }
            normalTelemetryAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
        }


        Map<String, Object> map = assembleTelemetryListForKAndTwoAndFeature(split, null, null, MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode(), telemetryList);
        Object telemetryArrayList = map.get("telemetryList");
        Set xAxis = (Set) map.get("xAxis");
        xAxis.stream().sorted(Comparator.comparing(x -> DateUtil.parse(x.toString(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));

        Integer min = null;
        if (algorithmParseObject.getInteger(HealthManagerConstant.MIN_STR) != null) {
            min = algorithmParseObject.getInteger("min");
        }

        Integer max = null;
        if (algorithmParseObject.getInteger(HealthManagerConstant.MAX_STR) != null) {
            max = algorithmParseObject.getInteger("max");
        }
        return MapUtil.builder(new HashMap<String, Object>(16))
                //遥测数据
                .put("xAxis", xAxis)
                //遥测数据
                .put("telemetryList", telemetryArrayList)
                //x轴
                .put("normalXaxis", normalAxis)
                //x轴
                .put("detectXaxis", detectAxis)
                //x轴
                .put("normalTelemetryAxis", normalTelemetryAxis)
                //x轴
                .put("detectTelemetryAxis", detectTelemetryAxis)
                //折线和散点图
                .put("normalSeries", normalLineList)
                //折线和散点图
                .put("detectSeries", detectLineList)
                //右侧数据
                .put("detect_value", algorithmParseObject.get("detect_value"))
                //右侧数据
                .put("normal_value", algorithmParseObject.get("normal_value"))
                //遥测数据
                .put("detectTelemetryList", detectTelemetryList)
                //遥测数据
                .put("normalTelemetryList", normalTelemetryList)
                //结论
                .put("msg", algorithmParseObject.get("msg"))
                .put("min", min)
                .put("max", max)
                .build();

    }

    /**
     * 门限值判断算法
     *
     * @param args          入参
     * @param telemetryList 遥测入参
     * @param modelTrain    模型入参
     * @return Map<String, Object>
     */
    //TODO: 1.此方法太长, 基本没有注释,无法维护和修改,需重构;2.方法名没按照驼峰要求命名
    private Map<String, Object> thresholdJudgmentAlgorithm(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain) {
        modelTrain.setTelemetryDataList(args);
        HttpResponse postResponse = HttpUtil.createRequest(Method.POST, algorithmParam.getThresholdJudgmentAlgorithm()).body(JSON.toJSONString(modelTrain)).execute();
        JSONArray jsonArrays = executionExceptionData(args, telemetryList, modelTrain, postResponse);
        JSONObject algorithmParseObject = jsonArrays.getObject(0, JSONObject.class);

        ArrayList<Object> series = new ArrayList<>();
        ThresholdJudgmentAlgorithmVo thresholdJudgmentAlgorithmVo = JSON.parseObject(algorithmParseObject.toJSONString(), ThresholdJudgmentAlgorithmVo.class);
        ArrayList<String> xAxis = new ArrayList<>();
        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk7graphArrayList = thresholdJudgmentAlgorithmVo.getTK7graph();

        String tk7graphPredictName = "";
        if (CollUtil.isNotEmpty(tk7graphArrayList)) {
            tk7graphPredictName = tk7graphArrayList.get(0).getParamCode();
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk7graphDTO : tk7graphArrayList) {
                xAxis.add(tk7graphDTO.getTime());
            }
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk7predictArrayList = thresholdJudgmentAlgorithmVo.getTK7predict();
        if (CollUtil.isNotEmpty(tk7predictArrayList)) {
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk7PredictDTO : tk7predictArrayList) {
                xAxis.add(tk7PredictDTO.getTime());
            }
        }

        String tk8graphPredictName = "";
        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk8graphArrayList = thresholdJudgmentAlgorithmVo.getTK8graph();
        if (CollUtil.isNotEmpty(tk8graphArrayList)) {
            tk8graphPredictName = tk8graphArrayList.get(0).getParamCode();
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk8predictArrayList = thresholdJudgmentAlgorithmVo.getTK8predict();

        HashMap<String, Object> tk7graphHashMap = new HashMap<>(3);
        ArrayList<Object> tk7graphList = getChangeMap(xAxis, null, tk7graphArrayList);
        tk7graphHashMap.put("data", tk7graphList);
        tk7graphHashMap.put("type", "line");
        tk7graphHashMap.put("name", tk7graphPredictName + "原始");
        series.add(tk7graphHashMap);

        HashMap<String, Object> tk7predictHashMap = new HashMap<>(3);
        ArrayList<Object> tk7predictList = getChangeMap(xAxis, null, tk7predictArrayList);
        tk7predictHashMap.put("data", tk7predictList);
        tk7predictHashMap.put("type", "line");
        tk7predictHashMap.put("name", tk7graphPredictName + "预测");
        series.add(tk7predictHashMap);

        HashMap<String, Object> tk8graphHashMap = new HashMap<>(3);
        ArrayList<Object> tk8graphList = getChangeMap(xAxis, null, tk8graphArrayList);
        tk8graphHashMap.put("data", tk8graphList);
        tk8graphHashMap.put("type", "line");
        tk8graphHashMap.put("name", tk8graphPredictName + "原始");
        series.add(tk8graphHashMap);

        HashMap<String, Object> tk8predictHashMap = new HashMap<>(3);
        ArrayList<Object> tk8predictList = getChangeMap(xAxis, null, tk8predictArrayList);
        tk8predictHashMap.put("data", tk8predictList);
        tk8predictHashMap.put("type", "line");
        tk8predictHashMap.put("name", tk8graphPredictName + "预测");
        series.add(tk8predictHashMap);

        String timeIndex = "";
        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> changeDTO = thresholdJudgmentAlgorithmVo.getChange();
        if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {
            timeIndex = thresholdJudgmentAlgorithmVo.getTimeIndex().toString();
        }

        return MapUtil.builder(new HashMap<String, Object>(6))
                //x轴
                .put("xAxis", xAxis)
                //折线
                .put("series", series)
                //右侧数据
                .put("gradientMap", changeDTO)
                //转折点索引下标
                .put("timeIndex", timeIndex)
                .put("threshold", modelTrain.getThreshold())
                .put("msg", thresholdJudgmentAlgorithmVo.getMsg())
                .build();
    }


    /**
     * 多参数上线保存数据
     *
     * @param parseDTO      解析算法结构数据
     * @param taskChildInfo 子任务信息
     * @param type          类型
     * @param taskInfo      任务对象
     * @param jsonArrays    算法数据
     */
    public void onlineParseSave(AlgorithmParseDTO parseDTO, TaskChildInfo taskChildInfo, String type, TaskInfo
            taskInfo, JSONArray jsonArrays) {
        if (type.equals(MultiParameterEnum.SLOPEALGORITHM.getCode())) {
            String maxName = null;
            Double maxGradient = null;
            for (Object jsonArray : jsonArrays) {
                ArrayList<MultiparatersDTO> valueDTOArrayList = new ArrayList<>();
                SlopeAlgorithmParseDTO algorithmParseDTO = JSONObject.parseObject(JSON.toJSONString(jsonArray), SlopeAlgorithmParseDTO.class);
                List<SlopeAlgorithmParseDTO.ValueDTO> value = algorithmParseDTO.getValue();
                if (CollUtil.isNotEmpty(value)) {
                    taskChildInfo.setDataSituation("(" + value.get(0).getX() + "," + value.get(value.size() - 1).getX() + ")");
                }
                ArrayList<MultiparatersDTO.SlopeValue> list = new ArrayList<>();
                for (SlopeAlgorithmParseDTO.ValueDTO dto : value) {
                    MultiparatersDTO.SlopeValue slopeValue = new MultiparatersDTO.SlopeValue();
                    slopeValue.setX(dto.getX());
                    slopeValue.setY(dto.getY());
                    list.add(slopeValue);
                }
                for (MultiparatersDTO.SlopeValue slopeValue : list) {
                    MultiparatersDTO valueDTO = new MultiparatersDTO();
                    valueDTO.setTimeIndex(algorithmParseDTO.getTimeIndex());
                    valueDTO.setErrorTime(algorithmParseDTO.getTime());
                    valueDTO.setTaskId(taskChildInfo.getTaskId());
                    valueDTO.setTaskChildId(taskChildInfo.getId());
                    valueDTO.setSateCode(taskChildInfo.getSatelliteCode());
                    valueDTO.setParamCode(algorithmParseDTO.getName());
                    valueDTO.setGradient(algorithmParseDTO.getGradient());
                    valueDTO.setType("slope");
                    valueDTO.setTime(slopeValue.getX());
                    valueDTO.setValue(slopeValue.getY());
                    valueDTO.setSlopeValueList(list);
                    valueDTOArrayList.add(valueDTO);
                }
                faultInfoMapper.insertDiagnoseParamsDataList(valueDTOArrayList);


                //计算斜率最大值
                String name = algorithmParseDTO.getName();
                Double gradient = algorithmParseDTO.getGradient();
                if (maxGradient == null) {
                    maxName = name;
                    maxGradient = gradient;
                } else {
                    if (0 > Double.compare(Math.abs(maxGradient), Math.abs(gradient))) {
                        maxGradient = gradient;
                        maxName = name;
                    }
                }
            }
            if (maxGradient != null) {
                taskInfo.setErrorSituation("1");
                taskChildInfo.setErrorSituation("1");
                MultiparatersDTO msgDTO = new MultiparatersDTO();
                msgDTO.setTaskId(taskChildInfo.getTaskId());
                msgDTO.setTaskChildId(taskChildInfo.getId());
                msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                msgDTO.setType("msg");
                ArrayList<MultiparatersDTO> msgList = CollUtil.newArrayList(msgDTO);
                faultInfoMapper.insertDiagnoseParamsDataList(msgList);
            } else {
                taskInfo.setErrorSituation("0");
                taskChildInfo.setErrorSituation("0");
            }
            taskInfoService.updateByIdSelective(taskInfo);
            taskChildInfoService.updateByIdSelective(taskChildInfo);

        } else {
            //异常提示信息 （废弃）
            List<ArrayList<AlgorithmParseDTO.AnomalyDTO>> anomalyArrayList = parseDTO.getAnomaly();
            if (CollUtil.isNotEmpty(anomalyArrayList)) {
                for (ArrayList<AlgorithmParseDTO.AnomalyDTO> dtos : anomalyArrayList) {
                    ArrayList<MultiparatersDTO> anomalyList = new ArrayList<>();
                    for (AlgorithmParseDTO.AnomalyDTO dto : dtos) {
                        MultiparatersDTO valueDTO = Convert.convert(MultiparatersDTO.class, dto);
                        valueDTO.setTaskId(taskChildInfo.getTaskId());
                        valueDTO.setTaskChildId(taskChildInfo.getId());
                        valueDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        valueDTO.setParamCode(dto.getName());
                        valueDTO.setType("anomaly");
                        anomalyList.add(valueDTO);
                    }
                    faultInfoMapper.insertDiagnoseParamsDataList(anomalyList);
                }
            }
            //右侧异常点数据
            List<AlgorithmParseDTO.ValueDTO> valueArrayList = parseDTO.getValue();
            if (CollUtil.isNotEmpty(valueArrayList)) {
                ArrayList<MultiparatersDTO> valueDTOList = new ArrayList<>();
                for (AlgorithmParseDTO.ValueDTO vto : valueArrayList) {
                    MultiparatersDTO valueDTO = Convert.convert(MultiparatersDTO.class, vto);
                    valueDTO.setTaskId(taskChildInfo.getTaskId());
                    valueDTO.setTaskChildId(taskChildInfo.getId());
                    valueDTO.setSateCode(taskChildInfo.getSatelliteCode());
                    valueDTO.setParamCode(valueDTO.getTime());
                    valueDTO.setType("value");
                    valueDTOList.add(valueDTO);
                }
                faultInfoMapper.insertDiagnoseParamsDataList(valueDTOList);
            }

            //绘图数据
            List<ArrayList<AlgorithmParseDTO.GraphDTO>> graphArrayList = parseDTO.getGraph();
            if (CollUtil.isNotEmpty(graphArrayList)) {
                taskChildInfo.setDataSituation("(" + graphArrayList.get(0).get(0).getTime() + "," + graphArrayList.get(0).get(graphArrayList.size() - 1).getTime() + ")");
                for (ArrayList<AlgorithmParseDTO.GraphDTO> graphDTOS : graphArrayList) {
                    ArrayList<MultiparatersDTO> graphDTOList = new ArrayList<>();
                    for (AlgorithmParseDTO.GraphDTO dto : graphDTOS) {
                        MultiparatersDTO valueDTO = Convert.convert(MultiparatersDTO.class, dto);
                        valueDTO.setTaskId(taskChildInfo.getTaskId());
                        valueDTO.setTaskChildId(taskChildInfo.getId());
                        valueDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        valueDTO.setParamCode(dto.getName());
                        valueDTO.setType("graph");
                        graphDTOList.add(valueDTO);
                    }
                    faultInfoMapper.insertDiagnoseParamsDataList(graphDTOList);
                }
            }

            if (StrUtil.isNotEmpty(parseDTO.getMsg())) {
                taskInfo.setErrorSituation("1");
                taskChildInfo.setErrorSituation("1");
                MultiparatersDTO setMsg = new MultiparatersDTO().setTaskId(taskChildInfo.getTaskId()).setTaskChildId(taskChildInfo.getId()).setSateCode(taskChildInfo.getSatelliteCode())
                        .setType("msg").setMsg(parseDTO.getMsg()).setParamCode(parseDTO.getParamCode());
                ArrayList<MultiparatersDTO> newArrayList = CollUtil.newArrayList(setMsg);
                faultInfoMapper.insertDiagnoseParamsDataList(newArrayList);
            } else {
                taskInfo.setErrorSituation("0");
                taskChildInfo.setErrorSituation("0");
            }
            taskInfoService.updateByIdSelective(taskInfo);
        }
    }

    /**
     * 双参数自动运行插入数据
     *
     * @param paramList            参数代号
     * @param algorithmParamObject 算法结果
     * @param taskChildInfo        子任务信息
     * @param taskInfo             任务信息
     */
    public void insertTwoOnline(String[] paramList, JSONObject algorithmParamObject, TaskChildInfo taskChildInfo, TaskInfo taskInfo) {
        int i = 1, j = 1, k = 1, l = 1, a = 1, b = 1, c = 1, d = 1;
        List<DiagnoseMultipleParametersData> list = new ArrayList<>();
        String startTime = null;
        String endTime = null;
        for (String code : paramList) {
            for (String key : algorithmParamObject.keySet()) {
                if (key.equals(code + "_detect") || key.equals(code + "_normal")) {
                    List<MultiparatersDTO> valueList = JSON.parseArray(algorithmParamObject.get(key).toString(), MultiparatersDTO.class);
                    if (key.equals(code + "_detect") && endTime == null) {
                        startTime = valueList.get(0).getTime();
                        endTime = valueList.get(valueList.size() - 1).getTime();
                    }
                    for (MultiparatersDTO twoValue : valueList) {
                        DiagnoseMultipleParametersData dto = new DiagnoseMultipleParametersData();
                        dto.setTaskId(taskChildInfo.getTaskId());
                        dto.setSateCode(taskChildInfo.getSatelliteCode());
                        dto.setTaskChildId(taskChildInfo.getId());
                        dto.setName(key);
                        dto.setTime(twoValue.getTime());
                        dto.setValue(twoValue.getValue());
                        list.add(dto);
                    }
                } else if ("scatter".equals(key) && i == 1) {
                    i++;
                    List<MultiparatersDTO> scatterList = JSON.parseArray(algorithmParamObject.get(key).toString(), MultiparatersDTO.class);
                    taskChildInfoService.updateByIdSelective(taskChildInfo);
                    for (MultiparatersDTO scatterValue : scatterList) {
                        DiagnoseMultipleParametersData dto = new DiagnoseMultipleParametersData();
                        dto.setTaskId(taskChildInfo.getTaskId());
                        dto.setSateCode(taskChildInfo.getSatelliteCode());
                        dto.setTaskChildId(taskChildInfo.getId());
                        dto.setName(key);
                        dto.setTime(scatterValue.getTime());
                        dto.setValue(scatterValue.getValue());
                        list.add(dto);
                    }
                } else if ("detect_value".equals(key) && j == 1) {
                    j++;
                    List<MultiparatersDTO> detectList = JSON.parseArray(algorithmParamObject.get(key).toString(), MultiparatersDTO.class);

                    for (MultiparatersDTO detect : detectList) {
                        DiagnoseMultipleParametersData dto = new DiagnoseMultipleParametersData();
                        dto.setTaskId(taskChildInfo.getTaskId());
                        dto.setSateCode(taskChildInfo.getSatelliteCode());
                        dto.setTaskChildId(taskChildInfo.getId());
                        dto.setValue(detect.getValue());
                        dto.setName(detect.getName());
                        dto.setType(key);
                        list.add(dto);
                    }
                } else if ("normal_value".equals(key) && k == 1) {
                    k++;
                    List<MultiparatersDTO> normalList = JSON.parseArray(algorithmParamObject.get(key).toString(), MultiparatersDTO.class);
                    for (MultiparatersDTO normal : normalList) {
                        DiagnoseMultipleParametersData dto = new DiagnoseMultipleParametersData();
                        dto.setTaskId(taskChildInfo.getTaskId());
                        dto.setSateCode(taskChildInfo.getSatelliteCode());
                        dto.setTaskChildId(taskChildInfo.getId());
                        dto.setValue(normal.getValue());
                        dto.setName(normal.getName());
                        dto.setType(key);
                        list.add(dto);
                    }
                } else if ("msg".equals(key) && l == 1) {
                    l++;
                    String msg = algorithmParamObject.getString("msg");
                    if (StrUtil.isNotEmpty(msg)) {
                        taskInfo.setErrorSituation("1");
                        taskChildInfo.setErrorSituation("1");
                        DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
                        msgDTO.setTaskId(taskChildInfo.getTaskId());
                        msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        msgDTO.setTaskChildId(taskChildInfo.getId());
                        msgDTO.setType(key);
                        msgDTO.setParamCode(algorithmParamObject.getString("param_code"));
                        msgDTO.setMsg(msg);
                        list.add(msgDTO);
                    } else {
                        taskInfo.setErrorSituation("0");
                        taskChildInfo.setErrorSituation("0");
                    }
                    taskInfoService.updateByIdSelective(taskInfo);
                    taskChildInfoService.updateByIdSelective(taskChildInfo);
                } else if ("detect_axis".equals(key) && a == 1) {
                    a++;
                    String detectAxisTitle = algorithmParamObject.getString("detect_axis");
                    if (StrUtil.isNotEmpty(detectAxisTitle)) {
                        DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
                        msgDTO.setTaskId(taskChildInfo.getTaskId());
                        msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        msgDTO.setTaskChildId(taskChildInfo.getId());
                        msgDTO.setType(key);
                        msgDTO.setTwoLogo(detectAxisTitle);
                        list.add(msgDTO);
                    }
                } else if ("normal_axis".equals(key) && b == 1) {
                    b++;
                    String normalAxisTitle = algorithmParamObject.getString("normal_axis");
                    if (StrUtil.isNotEmpty(normalAxisTitle)) {
                        DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
                        msgDTO.setTaskId(taskChildInfo.getTaskId());
                        msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        msgDTO.setTaskChildId(taskChildInfo.getId());
                        msgDTO.setType(key);
                        msgDTO.setTwoLogo(normalAxisTitle);
                        list.add(msgDTO);
                    }
                } else if ("min".equals(key) && c == 1) {
                    c++;
                    String min = algorithmParamObject.getString("min");
                    if (StrUtil.isNotEmpty(min)) {
                        DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
                        msgDTO.setTaskId(taskChildInfo.getTaskId());
                        msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        msgDTO.setTaskChildId(taskChildInfo.getId());
                        msgDTO.setType(key);
                        msgDTO.setTwoLogo(min);
                        list.add(msgDTO);
                    }
                } else if ("max".equals(key) && d == 1) {
                    d++;
                    String max = algorithmParamObject.getString("max");
                    if (StrUtil.isNotEmpty(max)) {
                        DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
                        msgDTO.setTaskId(taskChildInfo.getTaskId());
                        msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
                        msgDTO.setTaskChildId(taskChildInfo.getId());
                        msgDTO.setType(key);
                        msgDTO.setTwoLogo(max);
                        list.add(msgDTO);
                    }
                }
            }
        }
        taskChildInfo.setDataSituation("(" + startTime + "," + endTime + ")");
        taskChildInfoService.updateByIdSelective(taskChildInfo);
        List<List<DiagnoseMultipleParametersData>> partitionList = ListUtil.partition(list, 5000);
        System.out.println("双参数数据开始插入======================");
        for (List<DiagnoseMultipleParametersData> partition : partitionList) {
            diagnoseMultipleParametersDataMapper.insertDiagnoseMultipleParametersData(partition);
        }
        System.out.println("双参数数据插入完成======================");
    }

    /**
     * 插入双参数信息
     *
     * @param paramList            参数列表
     * @param algorithmParamObject 算法返回数据
     * @param taskChildInfo        子任务信息对象
     * @param taskInfo             任务信息对象
     */
    public void insertThresholdJudgmentOnline(String[] paramList, JSONObject algorithmParamObject, TaskChildInfo taskChildInfo, TaskInfo taskInfo) {
        ArrayList<Object> series = new ArrayList<>();
        ThresholdJudgmentAlgorithmVo thresholdJudgmentAlgorithmVo = JSONObject.parseObject(algorithmParamObject.toJSONString(), ThresholdJudgmentAlgorithmVo.class);

        ArrayList<DiagnoseMultipleParametersData> list = new ArrayList<>();
        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk7graphArrayList = thresholdJudgmentAlgorithmVo.getTK7graph();
        if (CollUtil.isNotEmpty(tk7graphArrayList)) {
            taskChildInfo.setDataSituation("(" + tk7graphArrayList.get(0).getTime() + "," + tk7graphArrayList.get(tk7graphArrayList.size() - 1).getTime() + ")");
            taskChildInfoService.updateByIdSelective(taskChildInfo);
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk7graphDTO : tk7graphArrayList) {
                DiagnoseMultipleParametersData tk7graph = Convert.convert(DiagnoseMultipleParametersData.class, tk7graphDTO);
                tk7graph.setTaskId(taskChildInfo.getTaskId());
                tk7graph.setSateCode(taskChildInfo.getSatelliteCode());
                tk7graph.setTaskChildId(taskChildInfo.getId());
                tk7graph.setType("TK7graph");
                if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {
                    tk7graph.setTimeIndex(thresholdJudgmentAlgorithmVo.getTimeIndex().toString());
                }

                list.add(tk7graph);
            }
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk7predictArrayList = thresholdJudgmentAlgorithmVo.getTK7predict();
        if (CollUtil.isNotEmpty(tk7predictArrayList)) {
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk7PredictDTO : tk7predictArrayList) {
                DiagnoseMultipleParametersData tk7Predict = Convert.convert(DiagnoseMultipleParametersData.class, tk7PredictDTO);
                tk7Predict.setTaskId(taskChildInfo.getTaskId());
                tk7Predict.setSateCode(taskChildInfo.getSatelliteCode());
                tk7Predict.setTaskChildId(taskChildInfo.getId());
                tk7Predict.setType("TK7predict");
                if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {
                    tk7Predict.setTimeIndex(thresholdJudgmentAlgorithmVo.getTimeIndex().toString());
                }

                list.add(tk7Predict);
            }
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk8graphArrayList = thresholdJudgmentAlgorithmVo.getTK8graph();
        if (CollUtil.isNotEmpty(tk8graphArrayList)) {
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk8graphDTO : tk8graphArrayList) {
                DiagnoseMultipleParametersData tk8graph = Convert.convert(DiagnoseMultipleParametersData.class, tk8graphDTO);
                tk8graph.setTaskId(taskChildInfo.getTaskId());
                tk8graph.setSateCode(taskChildInfo.getSatelliteCode());
                tk8graph.setTaskChildId(taskChildInfo.getId());
                tk8graph.setType("TK8graph");
                if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {

                    tk8graph.setTimeIndex(thresholdJudgmentAlgorithmVo.getTimeIndex().toString());
                }
                list.add(tk8graph);
            }
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> tk8predictArrayList = thresholdJudgmentAlgorithmVo.getTK8predict();
        ArrayList<Object> tk8predictList = new ArrayList<>();
        HashMap<String, Object> tk8predictHashMap = new HashMap<>(2);
        if (CollUtil.isNotEmpty(tk8predictArrayList)) {
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO tk8PredictDTO : tk8predictArrayList) {
                DiagnoseMultipleParametersData tk8predict = Convert.convert(DiagnoseMultipleParametersData.class, tk8PredictDTO);
                tk8predict.setTaskId(taskChildInfo.getTaskId());
                tk8predict.setSateCode(taskChildInfo.getSatelliteCode());
                tk8predict.setTaskChildId(taskChildInfo.getId());
                tk8predict.setType("TK8predict");
                if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {
                    tk8predict.setTimeIndex(thresholdJudgmentAlgorithmVo.getTimeIndex().toString());
                }

                list.add(tk8predict);
            }
        }

        List<ThresholdJudgmentAlgorithmVo.ChangeDTO> changeDTO = thresholdJudgmentAlgorithmVo.getChange();
        if (CollUtil.isNotEmpty(changeDTO)) {
            for (ThresholdJudgmentAlgorithmVo.ChangeDTO dto : changeDTO) {
                DiagnoseMultipleParametersData change = Convert.convert(DiagnoseMultipleParametersData.class, dto);
                change.setTaskId(taskChildInfo.getTaskId());
                change.setSateCode(taskChildInfo.getSatelliteCode());
                change.setTaskChildId(taskChildInfo.getId());
                change.setType("change");
                if (thresholdJudgmentAlgorithmVo.getTimeIndex() != null) {
                    change.setTimeIndex(thresholdJudgmentAlgorithmVo.getTimeIndex().toString());
                }

                list.add(change);
            }
        }


        if (StrUtil.isNotEmpty(thresholdJudgmentAlgorithmVo.getMsg())) {
            DiagnoseMultipleParametersData msgDTO = new DiagnoseMultipleParametersData();
            msgDTO.setTaskId(taskChildInfo.getTaskId());
            msgDTO.setSateCode(taskChildInfo.getSatelliteCode());
            msgDTO.setTaskChildId(taskChildInfo.getId());
            msgDTO.setType("msg");
            msgDTO.setParamCode(thresholdJudgmentAlgorithmVo.getParamCode());
            msgDTO.setMsg(thresholdJudgmentAlgorithmVo.getMsg());
            list.add(msgDTO);
            taskInfo.setErrorSituation("1");
            taskChildInfo.setErrorSituation("1");
        } else {
            taskInfo.setErrorSituation("0");
            taskChildInfo.setErrorSituation("0");
        }
        taskInfoService.updateByIdSelective(taskInfo);
        taskChildInfoService.updateByIdSelective(taskChildInfo);
        List<List<DiagnoseMultipleParametersData>> partitionList = ListUtil.partition(list, 5000);
        for (List<DiagnoseMultipleParametersData> partition : partitionList) {
            diagnoseMultipleParametersDataMapper.insertThresholdJudgmentData(partition);

        }
    }


    /**
     * 根据子任务Id获取多参数信息集合(事后诊断-自动运行子任务查看)
     *
     * @param taskChildId
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> getMultipleParametersList(Long taskChildId) {
        TaskChildInfo taskChildInfo = taskChildInfoService.selectById(taskChildId);

        //子任务开始结束时间
        DateTime childTaskStartTime=new DateTime(taskChildInfo.getStartTime().getTime());
        DateTime childTaskEndTime=new DateTime(taskChildInfo.getEndTime().getTime());

        TaskInfo taskInfo = taskInfoService.selectById(taskChildInfo.getTaskId());
        SatelliteCode satelliteCode = satelliteCodeService.selectOne(SatelliteCode.builder().satelliteCode(taskInfo.getSatelliteCode()).build());
        String[] paramCodeNameSplit = taskInfo.getParamCodeName().split(",");
        String[] splitString = taskInfo.getParams().split(",");
        String[] split = Arrays.stream(splitString).sorted().toArray(String[]::new);
        if (taskInfo.getMultiparameterAlgName().equals(MultiParameterEnum.SLOPEALGORITHM.getCode())) {
            /*X轴数据*/
            Set<String> xAxis = new LinkedHashSet<>();
            /*参数集合*/
            List<String> legendData = new ArrayList<>();
            /*Y轴数据包*/
            List<Map<String, Object>> seriesList = new ArrayList<>();
            /*斜率集合*/
            Map<String, Double> gradientMap = new LinkedHashMap<>();
            List<MultiparatersDTO> slopeList = faultInfoMapper.getSlopeList(taskChildId);
            Map<String, List<MultiparatersDTO>> slopeMap = slopeList.stream().collect(Collectors.groupingBy(MultiparatersDTO::getParamCode));
            String data = "";
            int i = 1;
            slopeMap.keySet().stream().forEach(item -> legendData.add(item));
            String errorParamCode = "";
            HashMap<String, Object> errorTimeMap = new HashMap<>(2);
            Double maxGradient = null;
            String timeIndex = "";
            String maxName = null;
            int j = 0;
            for (String key : slopeMap.keySet()) {
                for (String s : split) {
                    if (key.equals(s)) {
                        List<MultiparatersDTO> valueDTOList = slopeMap.get(s);
                        /*Y轴数据*/
                        List<Double> series = new ArrayList<>();
                        /*时间点数据*/
                        Map<String, Object> seriesMap = new LinkedHashMap<>();
                        String gradient = "";
                        String name = "";
                        int k = 0;
                        seriesMap.put("type", "line");
                        if (k == 0) {
                            ArrayList<Double> gradientList = new ArrayList<>();
                            for (MultiparatersDTO valueDTO : valueDTOList) {
                                if (valueDTO.getGradient() != null) {
                                    Double dtoGradient = new BigDecimal(valueDTO.getGradient()).setScale(6,RoundingMode.HALF_DOWN).doubleValue();
                                    gradientList.add(dtoGradient);
                                }else{
                                    valueDTO.setGradient(0D);
                                }
                                gradient = new BigDecimal(valueDTO.getGradient()).setScale(6,RoundingMode.HALF_DOWN).toString();
                                name = valueDTO.getParamCode();
                                if (maxGradient == null) {
                                    maxName = name;
                                    maxGradient = Double.parseDouble(gradient);
                                    List<MultiparatersDTO> dtoList1 = slopeMap.get(maxName);
                                    timeIndex = dtoList1.get(0).getTimeIndex();
                                } else {
                                    if (j == 1) {
                                        if (CollUtil.isNotEmpty(gradientList)) {
                                            Double gradientDouble = gradientList.get(0);
                                            if (0 > Double.compare(Math.abs(maxGradient), Math.abs(gradientDouble))) {
                                                maxGradient = Double.parseDouble(gradient);
                                                maxName = name;
                                                List<MultiparatersDTO> dtoList = slopeMap.get(maxName);
                                                if (CollUtil.isNotEmpty(dtoList)) {
                                                    String errorStartTime = dtoList.get(0).getErrorTime();
                                                    String errorEndTime = dtoList.get(dtoList.size() - 1).getTime();
                                                    timeIndex = dtoList.get(0).getTimeIndex();
                                                    errorTimeMap.put("errorStartTime", errorStartTime);
                                                    errorTimeMap.put("errorEndTime", errorEndTime);
                                                }
                                            }
                                        }
                                    }
                                }
                                gradientMap.put(name, Double.parseDouble(gradient));
                                xAxis.add(valueDTO.getTime());
                                series.add(valueDTO.getValue());
                            }
                            k++;
                        }
                        j++;
                        seriesMap.put("name", name);
                        seriesMap.put("data", series);
                        seriesList.add(seriesMap);
                        //处理最大曲线斜率
                        if(!CollectionUtils.isEmpty(gradientMap)){
                           List<Map.Entry<String,Double>> list=new ArrayList<>(gradientMap.entrySet());
                           Collections.sort(list,(o1,o2)->Double.compare(o1.getValue(), o2.getValue()));
                           if(Double.compare(list.get(0).getValue(),list.get(list.size()-1).getValue())!=0){
                               maxName=list.get(list.size()-1).getKey();
                               data = "参数" + maxName + "的斜率值较大";
                           }
                        }
                        errorParamCode = maxName;
                    }
                }
            }
            //查询截取遥测
            Map<String, Object> featureMap = assembleTelemetryListForKAndTwoAndFeature(split, taskChildInfo, xAxis.size(), MultiParameterEnum.SLOPEALGORITHM.getCode(), null);
            String[] paramCodeList = taskInfo.getParamCodeName().split(",");
            String errorParamCodeName = "";
            String searchKey = "";
            if (ArrayUtil.isNotEmpty(paramCodeList) && StrUtil.isNotEmpty(satelliteCode.getSatelliteName()) && StrUtil.isNotEmpty(errorParamCode)) {
                for (String key : paramCodeList) {
                    if (key.contains(errorParamCode)) {
                        errorParamCodeName = key;
                    }
                }
                searchKey = satelliteCode.getSatelliteName() + errorParamCodeName;
            } else if (StrUtil.isNotEmpty(errorParamCode)) {
                for (String key : paramCodeList) {
                    if (key.contains(errorParamCode)) {
                        errorParamCodeName = key;
                    }
                }
                searchKey = errorParamCodeName;
            } else if (StrUtil.isNotEmpty(satelliteCode.getSatelliteName())) {
                searchKey = satelliteCode.getSatelliteName();
            }
            return MapUtil.builder(new HashMap<String, Object>(12))
                    .put("xAxis", xAxis)
                    .put("downxAxis", xAxis)
                    .put("series", seriesList)
                    .put("legend", legendData)
                    .put("gradientMap", gradientMap)
                    .put("calResult", "")
                    .put("telemetryList", featureMap.get("telemetryList"))
                    .put("msg", data)
                    .put("errorParamCode", errorParamCode)
                    .put("errorTimeMap", errorTimeMap)
                    .put("searchKey", searchKey)
                    .put("timeIndex", timeIndex)
                    .put("type", Integer.parseInt(MultiParameterEnum.SLOPEALGORITHM.getCode())).build();
        } else if (taskInfo.getMultiparameterAlgName().equals(MultiParameterEnum.MEANFEATUREALGORITHM.getCode())) {
            //均值
            Map<String, Object> assembleAnomalyAndValue = assembleAnomalyAndValue(taskInfo, taskChildId);
            ArrayList<String> legend = (ArrayList<String>) assembleAnomalyAndValue.get("legend");
            if (CollUtil.isEmpty(legend)) {
                legend = new ArrayList<String>();
            }
            String data = (String) assembleAnomalyAndValue.get("data");
            List<MultiparatersDTO> gradientMap = (List<MultiparatersDTO>) assembleAnomalyAndValue.get("gradientMap");
            if (CollUtil.isEmpty(gradientMap)) {
                gradientMap = new ArrayList<MultiparatersDTO>();
            }
            LinkedList<Object> series = new LinkedList<>();
            LinkedHashSet<String> xAxis = new LinkedHashSet<>();
            List<MultiparatersDTO> graphList = faultInfoMapper.getGraphList(taskChildId);
            if (CollUtil.isEmpty(graphList)) {
                series = new LinkedList<>();
            } else {
                Map<String, List<MultiparatersDTO>> graphMap = graphList.stream().collect(Collectors.groupingBy(MultiparatersDTO::getParamCode));
                TreeSet<String> keySet = graphMap.keySet().stream().collect(Collectors.toCollection(TreeSet::new));
                for (String key : keySet) {
                    HashMap<String, Object> seriesMap = new LinkedHashMap<>();
                    List<Double> valueData = graphMap.get(key).stream().map(item -> item.getValue()).collect(Collectors.toList());
                    if (CollUtil.isEmpty(valueData)) {
                        valueData = new ArrayList<>();
                    } else {
                        graphMap.get(key).stream().forEach(item -> xAxis.add(item.getTime()));
                        seriesMap.put("type", "line");
                        if ("threshold".equals(key)) {
                            seriesMap.put("name", "均值中位数");
                        } else {
                            seriesMap.put("name", key);
                        }

                        seriesMap.put("data", valueData);
                    }
                    if (seriesMap.containsKey("threshold")) {
                        series.addLast(seriesMap);
                    } else {
                        series.add(seriesMap);
                    }
                }
            }

            //查询截取遥测长度
            Map<String, Object> featureMap = assembleTelemetryListForKAndTwoAndFeature(split, taskChildInfo, xAxis.size(), MultiParameterEnum.MEANFEATUREALGORITHM.getCode(), null);
            List<Map<String, Object>> telemetryList = (List<Map<String, Object>>) featureMap.get("telemetryList");
            Set<String> xLineAxis = new LinkedHashSet<>();
            if (ArrayUtil.isNotEmpty(paramCodeNameSplit)) {
                for (Map<String, Object> map : telemetryList) {
                    List list = (List) map.get("data");
                    for (Object o : list) {
                        List list1 = (List) o;
                        String o1 = (String) list1.get(0);
                        xLineAxis.add(o1);
                    }
                }
            }
            return MapUtil.builder(new HashMap<String, Object>(12))
                    .put("searchKey", assembleAnomalyAndValue.get("searchKey"))
                    .put("xLineAxis", xLineAxis)
                    .put("xAxis", xAxis)
                    .put("downxAxis", xAxis)
                    .put("series", series)
                    .put("legend", legend)
                    .put("gradientMap", gradientMap)
                    .put("calResult", "")
                    .put("telemetryList", telemetryList)
                    .put("msg", assembleAnomalyAndValue.get("msg"))
                    .put("errorParamCode", assembleAnomalyAndValue.get("errorParamCode"))
                    .put("errorTimeMap", assembleAnomalyAndValue.get("errorTimeMap"))
                    .put("type", Integer.parseInt(MultiParameterEnum.MEANFEATUREALGORITHM.getCode())).build();
        } else if (taskInfo.getMultiparameterAlgName().equals(MultiParameterEnum.KNEARESTNEIGHBORALGORITHM.getCode())) {

            Map<String, Object> assembleAnomalyAndValue = assembleAnomalyAndValue(taskInfo, taskChildId);
            ArrayList<String> legend = (ArrayList<String>) assembleAnomalyAndValue.get("legend");
            String data = (String) assembleAnomalyAndValue.get("data");
            List<MultiparatersDTO> gradientMap = (List<MultiparatersDTO>) assembleAnomalyAndValue.get("gradientMap");

            //k邻近提示对比语句
            StringBuilder builder = new StringBuilder();
            if (CollUtil.isNotEmpty(gradientMap)) {
                double sum = 0;
                double average = 0;
                ArrayList<Double> doubleArrayList = new ArrayList<>();
                for (MultiparatersDTO dto : gradientMap) {
                    Double value = new BigDecimal(dto.getValue()).setScale(6,RoundingMode.HALF_DOWN).doubleValue();
                    dto.setValue(value);
                    doubleArrayList.add(value);
                }
                for (int i = 0; i <= doubleArrayList.size() - 1; i++) {
                    sum += doubleArrayList.get(i);
                }
                ArrayList<Object> tipsList = new ArrayList<>();
                average = (sum / doubleArrayList.size()) * 2;
                for (MultiparatersDTO dto : gradientMap) {
                    if (dto.getValue() > average) {
                        tipsList.add(dto.getParamCode());
                    }
                }
                if (CollUtil.isNotEmpty(tipsList)) {
                    builder.append(tipsList.toString().replace("[", "").replace("]", "") + "大于2倍邻近距离均值");
                }
            }


            //散点
            HashMap<Object, ArrayList<ArrayList<Object>>> graphMap = new HashMap<>(2);
            List<MultiparatersDTO> graphList = faultInfoMapper.getGraphList(taskChildId);
            Integer dataSize = null;
            if (CollUtil.isNotEmpty(graphList)) {
                Map<String, List<MultiparatersDTO>> valueMap = graphList.stream().collect(Collectors.groupingBy(MultiparatersDTO::getParamCode));
                TreeSet<String> keySet = valueMap.keySet().stream().collect(Collectors.toCollection(TreeSet::new));
                String graphName = "";
                for (String key : keySet) {
                    List<MultiparatersDTO> valueDTOList = valueMap.get(key);
                    dataSize = valueDTOList.size();
                    ArrayList<ArrayList<Object>> xygraphList = new ArrayList<>();
                    for (MultiparatersDTO valueDTO : valueDTOList) {
                        String graphTime = valueDTO.getTime();
                        Double graphvalue = valueDTO.getValue();
                        ArrayList<Object> list = new ArrayList<>();
                        list.add(graphTime);
                        list.add(graphvalue);
                        xygraphList.add(list);
                    }
                    graphMap.put(key, xygraphList);
                }
            }

            Map<String, Object> featureMap = assembleTelemetryListForKAndTwoAndFeature(split, taskChildInfo, dataSize, MultiParameterEnum.KNEARESTNEIGHBORALGORITHM.getCode(), null);
            return MapUtil.builder(new HashMap<String, Object>(12))
                    .put("msg", assembleAnomalyAndValue.get("msg"))
                    .put("searchKey", assembleAnomalyAndValue.get("searchKey"))
                    .put("xAxis", featureMap.get("xAxis")).put("graphMap", graphMap)
                    .put("legend", legend)
                    .put("gradientMap", gradientMap)
                    .put("downxAxis", featureMap.get("xAxis"))
                    .put("msg", assembleAnomalyAndValue.get("msg"))
                    .put("errorParamCode", assembleAnomalyAndValue.get("errorParamCode"))
                    .put("errorTimeMap", assembleAnomalyAndValue.get("errorTimeMap"))
                    .put("telemetryList", featureMap.get("telemetryList"))
                    .put("tips", builder)
                    .put("type", Integer.parseInt(MultiParameterEnum.KNEARESTNEIGHBORALGORITHM.getCode())).build();

        } else if (taskInfo.getMultiparameterAlgName().equals(MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode())) {
            String sql = "select * from tb_diagnose_multiple_parameters_data where task_child_id = " + taskChildId;

            String detectSql = sql + " and name is not null and name like '%_detect'";
            List<DiagnoseMultipleParametersData> detectLists = dataQualityService.getClickHouseBySql(detectSql);

            ArrayList<Object> detectLineList = new ArrayList<>();
            Map<String, List<DiagnoseMultipleParametersData>> detectList = detectLists.stream().collect(Collectors.groupingBy(DiagnoseMultipleParametersData::getName));
            for (String key : detectList.keySet()) {
                List<DiagnoseMultipleParametersData> detectArrayList = detectList.get(key);
                ArrayList<Object> detectDataList = new ArrayList<>();
                HashMap<String, Object> map = new HashMap<>(2);
                map.put("name", key.replace("_detect", "诊断"));
                map.put("type", "line");
                //detectArrayList按MultiparatersDTO的time先转为时间格式再按升序排序
                detectArrayList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                for (DiagnoseMultipleParametersData arraylist : detectArrayList) {
                    ArrayList<Object> list1 = new ArrayList<>();
                    list1.add(arraylist.getTime());
                    list1.add(arraylist.getValue());
                    detectDataList.add(list1);
                }
                map.put("data", detectDataList);
                detectLineList.add(map);
            }

            ArrayList<Object> normalLineList = new ArrayList<>();
            String normalSql = sql + " and name is not null and name like '%_normal'";
            //normalSql=normalSql+" and time >="+"'"+childTaskStartTime+"'"+" and time<="+"'"+childTaskEndTime+"'";
            List<DiagnoseMultipleParametersData> normalLists = dataQualityService.getClickHouseBySql(normalSql);
            Map<String, List<DiagnoseMultipleParametersData>> normalList = normalLists.stream().collect(Collectors.groupingBy(DiagnoseMultipleParametersData::getName));
            for (String key : normalList.keySet()) {
                List<DiagnoseMultipleParametersData> normalArrayList = normalList.get(key);
                ArrayList<Object> normalDataList = new ArrayList<>();
                HashMap<String, Object> map = new HashMap<>(2);
                map.put("name", key.replace("_normal", "诊断"));
                map.put("type", "line");
                normalArrayList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                for (DiagnoseMultipleParametersData array : normalArrayList) {
                    ArrayList<Object> list = new ArrayList<>();
                    list.add(array.getTime());
                    list.add(array.getValue());
                    normalDataList.add(list);
                }
                map.put("data", normalDataList);
                normalLineList.add(map);
            }

            String scatterSql = sql + " and name is not null and  name = 'scatter'";
            List<DiagnoseMultipleParametersData> scatterList = dataQualityService.getClickHouseBySql(scatterSql);
            ArrayList<Object> scatterDataList = new ArrayList<>();
            HashMap<String, Object> objectHashMap = new HashMap<>(3);
            for (DiagnoseMultipleParametersData dto : scatterList) {
                ArrayList<Object> scatterTimeValueList = new ArrayList<>();
                scatterTimeValueList.add(dto.getTime());
                scatterTimeValueList.add(dto.getValue());
                scatterDataList.add(scatterTimeValueList);
            }
            objectHashMap.put("name", "散点");
            objectHashMap.put("chartType", "scatter");
            objectHashMap.put("data", scatterDataList);
            detectLineList.add(objectHashMap);

            //右侧数据
            String detectValueSql = sql + " and type is not null and  type = 'detect_value'";
            List<DiagnoseMultipleParametersData> detectValueCollect = dataQualityService.getClickHouseBySql(detectValueSql);
            List<DiagnoseMultipleParametersData> detectValue = detectValueCollect.stream().distinct().collect(Collectors.toList());
            String normalValuSql = sql + " and type is not null and  type = 'normal_value'";
            List<DiagnoseMultipleParametersData> normalValue = dataQualityService.getClickHouseBySql(normalValuSql);


            Map<String, Object> featureMap = assembleTelemetryListForKAndTwoAndFeature(split, taskChildInfo, null, MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode(), null);

            ArrayList<String> detectAxis = new ArrayList<>();
            List<HashMap<String, DateTime>> dateTimeList = new ArrayList<>();
            String detectAxisSql = sql + " and type ='detect_axis'";
            List<DiagnoseMultipleParametersData> detectAxisList = dataQualityService.getClickHouseBySql(detectAxisSql);
            if (CollUtil.isNotEmpty(detectAxisList)) {
                DiagnoseMultipleParametersData detectAxisData = detectAxisList.get(0);
                String detectAxisStr = detectAxisData.getTwoLogo();
                if (StrUtil.isNotEmpty(detectAxisStr)) {
                    String detectAxisStrSql = sql + " and name ='" + detectAxisStr + "' ";
                    detectAxisStrSql=detectAxisStrSql+" and time >="+"'"+childTaskStartTime+"'"+" and time<="+"'"+childTaskEndTime+"'";
                    List<DiagnoseMultipleParametersData> detectListData = dataQualityService.getClickHouseBySql(detectAxisStrSql);
                    if (CollUtil.isNotEmpty(detectListData)) {
                        for (DiagnoseMultipleParametersData detectData : detectListData) {
                            detectAxis.add(detectData.getTime());
                        }
                        detectAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                        HashMap<String, DateTime> detectTimeMap = new HashMap<>(2);
                        String detectStartTimeStr = detectAxis.get(0);
                        if (detectStartTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                            detectStartTimeStr.substring(0, detectStartTimeStr.length() - 4);
                        }
                        DateTime detectStartTime = DateUtil.parse(detectStartTimeStr, "yyyy-MM-dd HH:mm:ss");
                        String detectEndTimeStr = detectAxis.get(detectAxis.size() - 1);
                        if (detectEndTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                            detectEndTimeStr.substring(0, detectEndTimeStr.length() - 4);
                        }
                        DateTime detectEndTime = DateUtil.parse(detectEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                        detectTimeMap.put("detectStartTime", detectStartTime);
                        detectTimeMap.put("detectEndTime", detectEndTime);
                        dateTimeList.add(detectTimeMap);
                    }
                }
            }

            ArrayList<String> normalAxis = new ArrayList<>();
            String normalAxisSql = sql + " and type ='normal_axis'";
            List<DiagnoseMultipleParametersData> normalAxisList = dataQualityService.getClickHouseBySql(normalAxisSql);
            if (CollUtil.isNotEmpty(normalAxisList)) {
                DiagnoseMultipleParametersData normalAxisData = normalAxisList.get(0);
                String normalAxisStr = normalAxisData.getTwoLogo();
                if (StrUtil.isNotEmpty(normalAxisStr)) {
                    String normalAxisStrSql = sql + " and name ='" + normalAxisStr + "' ";
                    //normalAxisStrSql=normalAxisStrSql+" and time >="+"'"+childTaskStartTime+"'"+" and time<="+"'"+childTaskEndTime+"'";
                    List<DiagnoseMultipleParametersData> normalListData = dataQualityService.getClickHouseBySql(normalAxisStrSql);
                    if (CollUtil.isNotEmpty(normalListData)) {
                        for (DiagnoseMultipleParametersData normalData : normalListData) {
                            normalAxis.add(normalData.getTime());
                        }
                        normalAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
                        HashMap<String, DateTime> normalTimeMap = new HashMap<>(2);
                        String normalStartTimeStr = normalAxis.get(0);
                        if (normalStartTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                            normalStartTimeStr.substring(0, normalStartTimeStr.length() - 4);
                        }
                        DateTime normalStartTime = DateUtil.parse(normalStartTimeStr, "yyyy-MM-dd HH:mm:ss");
                        String normalEndTimeStr = normalAxis.get(normalAxis.size() - 1);
                        if (normalEndTimeStr.length() == HealthManagerConstant.TIME_TWENTY_THREE) {
                            normalEndTimeStr.substring(0, normalEndTimeStr.length() - 4);
                        }
                        DateTime normalEndTime = DateUtil.parse(normalEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                        normalTimeMap.put("normalStartTime", normalStartTime);
                        normalTimeMap.put("normalEndTime", normalEndTime);
                        dateTimeList.add(normalTimeMap);
                    }
                }
            }

            List<Map<String, Object>> normalTelemetryList = new ArrayList<>();
            List<Map<String, Object>> detectTelemetryList = new ArrayList<>();
            if (ArrayUtil.isNotEmpty(split) && CollUtil.isNotEmpty(dateTimeList)) {
                for (HashMap<String, DateTime> map : dateTimeList) {
                    for (String paramCode : split) {
                        // 查询遥测数据
                        TelemetryDto telemetryDto1 = new TelemetryDto();
                        telemetryDto1.setSatelliteCode(taskInfo.getSatelliteCode());
                        telemetryDto1.setParamCodes(new String[]{paramCode});
                        if (map.containsKey("detectStartTime") && map.containsKey("detectEndTime")) {
                            telemetryDto1.setStartTime(map.get("detectStartTime"));
                            telemetryDto1.setEndTime(map.get("detectEndTime"));
                        } else {
                            telemetryDto1.setStartTime(map.get("normalStartTime"));
                            telemetryDto1.setEndTime(map.get("normalEndTime"));
                        }
                        Map<String, List<TelemetryData>> map1 = diagnoseService.selectTelemetryData(telemetryDto1);
                        List<TelemetryData> ycList = map1.get(paramCode);
                        List<ArrayList<String>> collect = ycList.stream().map(x -> CollUtil.newArrayList(x.getTime(), x.getValue())).collect(Collectors.toList());
                        Map<String, Object> telemetry = new LinkedHashMap<>();
                        telemetry.put("name", paramCode + "正常");
                        telemetry.put("data", collect);
                        if (map.containsKey("detectStartTime") && map.containsKey("detectEndTime")) {
                            detectTelemetryList.add(telemetry);
                        } else {
                            normalTelemetryList.add(telemetry);
                        }

                    }

                }
            }

            List<String> detectTelemetryAxis = new ArrayList<>();
            if (CollUtil.isNotEmpty(detectTelemetryList)) {
            List detectTelemetryArrayList = (List) detectTelemetryList.get(0).get("data");
            if (CollUtil.isNotEmpty(detectTelemetryArrayList)) {
                for (Object o : detectTelemetryArrayList) {
                    List list1 = (List) o;
                    String o1 = (String) list1.get(0);
                    detectTelemetryAxis.add(o1);
                }
            }
                detectTelemetryAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            }

            List<String> normalTelemetryAxis = new ArrayList<>();
            if (CollUtil.isNotEmpty(normalTelemetryList)) {
                List normalTelemetryArrayList = (List) normalTelemetryList.get(0).get("data");
                for (Object o1 : normalTelemetryArrayList) {
                    List oList = (List) o1;
                    String timeStr = (String) oList.get(0);
                    normalTelemetryAxis.add(timeStr);
                }
                normalTelemetryAxis.sort(Comparator.comparing(x -> DateUtil.parse(x, "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            }


            //msg提示语句 searchKey
            String msgSql = sql + " and type is not null and  type = 'msg'";
            List<DiagnoseMultipleParametersData> msgLists = dataQualityService.getClickHouseBySql(msgSql);
            Map<String, List<DiagnoseMultipleParametersData>> msgList = msgLists.stream().collect(Collectors.groupingBy(DiagnoseMultipleParametersData::getType));
            String msg = "";
            String errorParamCode = "";
            String searchKey = "";
            ArrayList<String> errorParamCodeList = new ArrayList<>();
            if (CollUtil.isNotEmpty(msgList)) {
                msg = msgList.get("msg").get(0).getMsg();
                errorParamCode = msgList.get("msg").get(0).getParamCode();
                String[] codes = errorParamCode.split(",");
                for (String code : codes) {
                    System.out.println(code);
                    errorParamCodeList.add(code);
                }
                searchKey = (String) getSearchKey(taskInfo, errorParamCodeList).get("searchKey");
            }


            //定死
            HashMap<String, Object> errorTimeMap = new HashMap<>(2);
            errorTimeMap.put("errorStartTime", "");
            errorTimeMap.put("errorEndTime", "");

            Double max = null;
            String maxSql = sql + " and type ='max'";
            List<DiagnoseMultipleParametersData> maxCollect = dataQualityService.getClickHouseBySql(maxSql);
            if (CollUtil.isNotEmpty(maxCollect)) {
                DiagnoseMultipleParametersData maxData = maxCollect.get(0);
                if (BeanUtil.isNotEmpty(maxData)) {
                    max = Double.valueOf(maxData.getTwoLogo());
                }
            }

            Integer min = null;
            String minSql = sql + " and type ='min'";
            List<DiagnoseMultipleParametersData> minCollect = dataQualityService.getClickHouseBySql(minSql);
            if (CollUtil.isNotEmpty(minCollect)) {
                DiagnoseMultipleParametersData minData = minCollect.get(0);
                if (BeanUtil.isNotEmpty(minData)) {
                    min = Integer.valueOf(minData.getTwoLogo());
                }
            }

            return MapUtil.builder(new HashMap<String, Object>(16))
                    .put("normalXaxis", normalAxis)
                    .put("detectXaxis", detectAxis)
                    .put("normalTelemetryAxis", normalTelemetryAxis)
                    .put("detectTelemetryAxis", detectTelemetryAxis)
                    .put("normalSeries", normalLineList)
                    .put("detectSeries", detectLineList)
                    .put("detectTelemetryList", detectTelemetryList)
                    .put("normalTelemetryList", normalTelemetryList)
                    .put("min", min)
                    .put("max", max)
                    .put("msg", msg)
                    .put("errorParamCode", errorParamCode)
                    .put("errorTimeMap", errorTimeMap)
                    .put("searchKey", searchKey)
                    .put("xAxis", featureMap.get("xAxis"))
                    .put("detect_value", detectValue)
                    .put("normal_value", normalValue)
                    .put("telemetryList", featureMap.get("telemetryList"))
                    .put("type", Integer.parseInt(MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode())).build();

        } else if (taskInfo.getMultiparameterAlgName().

                equals(MultiParameterEnum.THRESHOLDJUDGMENTALGORITHM.getCode())) {
            List<DiagnoseMultipleParametersData> dataList = diagnoseMultipleParametersDataMapper.selectDataList(taskChildId);
            Map<String, List<DiagnoseMultipleParametersData>> collect = dataList.stream().collect(Collectors.groupingBy(DiagnoseMultipleParametersData::getType));
            ArrayList<String> xAxis = new ArrayList<>();
            ArrayList<Object> series = new ArrayList<>();

            String tk7graphPredictName = "";
            String tk8graphPredictName = "";
            String timeIndex = "";
            List<DiagnoseMultipleParametersData> tk7graphList = collect.get("TK7graph");
            tk7graphList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            if (CollUtil.isNotEmpty(tk7graphList)) {
                tk7graphPredictName = tk7graphList.get(0).getParamCode();
                timeIndex = tk7graphList.get(0).getTimeIndex();
                for (DiagnoseMultipleParametersData tk7graphDTO : tk7graphList) {
                    xAxis.add(tk7graphDTO.getTime());
                }
            }

            List<DiagnoseMultipleParametersData> tk7predictList = collect.get("TK7predict");
            tk7predictList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            if (CollUtil.isNotEmpty(tk7predictList)) {
                for (DiagnoseMultipleParametersData tk7predictDTO : tk7predictList) {
                    xAxis.add(tk7predictDTO.getTime());
                }
            }

            List<DiagnoseMultipleParametersData> tk8graphList = collect.get("TK8graph");
            tk8graphList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            if (CollUtil.isNotEmpty(tk8graphList)) {
                tk8graphPredictName = tk8graphList.get(0).getParamCode();
            }

            List<DiagnoseMultipleParametersData> tk8predictList = collect.get("TK8predict");
            tk8predictList.sort(Comparator.comparing(x -> DateUtil.parse(x.getTime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime()));
            HashMap<String, Object> tk7graphHashMap = new HashMap<>(3);
            List<Object> tk7graphArrayList = getChangeMap(xAxis, tk7graphList, null);
            tk7graphHashMap.put("data", tk7graphArrayList);
            tk7graphHashMap.put("name", tk7graphPredictName + "原始");
            tk7graphHashMap.put("type", "line");
            series.add(tk7graphHashMap);

            HashMap<String, Object> tk7predictHashMap = new HashMap<>(3);
            List<Object> tk7predictArrayList = getChangeMap(xAxis, tk7predictList, null);
            tk7predictHashMap.put("data", tk7predictArrayList);
            tk7predictHashMap.put("name", tk7graphPredictName + "预测");
            tk7predictHashMap.put("type", "line");
            series.add(tk7predictHashMap);

            HashMap<String, Object> tk8graphHashMap = new HashMap<>(3);
            List<Object> tk8graphArrayList = getChangeMap(xAxis, tk8graphList, null);
            tk8graphHashMap.put("data", tk8graphArrayList);
            tk8graphHashMap.put("name", tk8graphPredictName + "原始");
            tk8graphHashMap.put("type", "line");
            series.add(tk8graphHashMap);


            HashMap<String, Object> tk8predictHashMap = new HashMap<>(3);
            List<Object> tk8predictArrayList = getChangeMap(xAxis, tk8predictList, null);
            tk8predictHashMap.put("data", tk8predictArrayList);
            tk8predictHashMap.put("name", tk8graphPredictName + "预测");
            tk8predictHashMap.put("type", "line");
            series.add(tk8predictHashMap);

            List<DiagnoseMultipleParametersData> changeList = collect.get("change");
            if(!CollectionUtils.isEmpty(changeList)){
                for(DiagnoseMultipleParametersData diagnoseMultipleParametersData:changeList){
                    Double value = diagnoseMultipleParametersData.getValue();
                    if(null!=value){
                        value=new BigDecimal(value).setScale(6,RoundingMode.HALF_DOWN).doubleValue();
                        diagnoseMultipleParametersData.setValue(value);
                   }
                }
            }

            //提示
            String errorParamCode = "";
            String searchKey = "";
            List<DiagnoseMultipleParametersData> msgList = collect.get("msg");
            String msg = "";
            ArrayList<String> errorParamCodeList = new ArrayList<>();
            if (CollUtil.isNotEmpty(msgList)) {
                String[] paranCode = msgList.get(0).getParamCode().split(",");
                for (String code : paranCode) {
                    errorParamCodeList.add(code);
                }
                errorParamCode = msgList.get(0).getParamCode();
                searchKey = (String) getSearchKey(taskInfo, errorParamCodeList).get("searchKey");
                msg = msgList.get(0).getMsg();
            }
            //定死
            HashMap<String, Object> errorTimeMap = new HashMap<>(2);
            errorTimeMap.put("errorStartTime", "");
            errorTimeMap.put("errorEndTime", "");
            return MapUtil.builder(new HashMap<String, Object>(10))
                    .put("errorParamCode", errorParamCode)
                    .put("errorTimeMap", errorTimeMap)
                    //x轴
                    .put("xAxis", xAxis)
                    //折线
                    .put("series", series)
                    //右侧数据
                    .put("gradientMap", changeList)
                    //转折点索引下标
                    .put("timeIndex", timeIndex)
                    .put("msg", msg)
                    .put("threshold", taskInfo.getThreshold())
                    .put("searchKey", searchKey)
                    .put("type", Integer.parseInt(MultiParameterEnum.THRESHOLDJUDGMENTALGORITHM.getCode()))
                    .build();
        }
        return new HashMap<>(2);
    }

    /**
     * 处理参数异常问题
     *
     * @param args          入参
     * @param telemetryList 遥测入参
     * @param postResponse  响应数据
     * @return JSONArray
     */
    public JSONArray executionExceptionData(Map<String, Object> args, List<Map<String, Object>> telemetryList, ModelTrain modelTrain, HttpResponse postResponse) {
        /*返回结果*/
        if (postResponse.getStatus() != HttpStatus.HTTP_OK) {
            // 返回为空默认为解析失败
            throw new HealthException("算法调用失败");
        }
        JSONArray jsonArrays = null;
        try {
            jsonArrays = JSONArray.parseArray(postResponse.body());
        } catch (Exception e) {
            JSONObject map1 = JSONObject.parseObject(postResponse.body(), JSONObject.class);
            if (map1.getInteger(HealthManagerConstant.STATUS_CODE).equals(ResultEnum.FAIL.getCode())) {
                throw new HealthException(map1.getString("msg"));
            }
        }
        return jsonArrays;
    }

    /**
     * 处理时间线中断
     *
     * @param xAxis     完整横坐标
     * @param list      查看子任务横坐标
     * @param trailList 手动试算横坐标
     * @return ArrayList<Object>
     */
    public ArrayList<Object> getChangeMap
    (ArrayList<String> xAxis, List<DiagnoseMultipleParametersData> list, List<ThresholdJudgmentAlgorithmVo.ChangeDTO> trailList) {
        ArrayList<Object> allArrayList = new ArrayList<>();
        if (CollUtil.isNotEmpty(xAxis)) {
            for (String xAxi : xAxis) {
                boolean found = false;
                ArrayList<Object> arrayList = new ArrayList<>();
                if (CollUtil.isNotEmpty(list)) {
                    for (DiagnoseMultipleParametersData array : list) {
                        if (array.getTime().equals(xAxi)) {
                            arrayList.add(xAxi);
                            arrayList.add(array.getValue());
                            found = true;
                            allArrayList.add(arrayList);
                            break;
                        }
                    }
                } else {
                    for (ThresholdJudgmentAlgorithmVo.ChangeDTO array : trailList) {
                        if (array.getTime().equals(xAxi)) {
                            arrayList.add(xAxi);
                            arrayList.add(array.getValue());
                            found = true;
                            allArrayList.add(arrayList);
                            break;
                        }
                    }
                }

                if (!found) {
                    arrayList.add(xAxi);
                    arrayList.add(null);
                    allArrayList.add(arrayList);

                }
            }
        } else {
            allArrayList = new ArrayList<>();
        }
        return allArrayList;
    }

    /**
     * 解析右侧和异常提示信息
     *
     * @param algorithmParseObject 算法数据对象
     * @return Map<String, Object>
     */
    public Map<String, Object> parseAnomalyAndValueData(JSONObject algorithmParseObject) {
        //异常提示
        ArrayList<Set<String>> tipsList = new ArrayList<>();
        //右侧
        ArrayList<String> paramList = new ArrayList<>();

        HashMap<String, Object> map = new HashMap<>(3);

        JSONArray anomalyObject = algorithmParseObject.getObject("anomaly", JSONArray.class);
        String data = "";
        if (CollUtil.isNotEmpty(anomalyObject) && anomalyObject instanceof JSONArray) {
            for (Object o : anomalyObject) {
                JSONObject objectList = JSONObject.parseObject(JSON.toJSONString(o), JSONObject.class);
                Set<String> keyList = objectList.keySet();
                tipsList.add(keyList);
            }
            data = "参数" + tipsList.toString().replace("[", "").replace("]", "") + "检测为异常！";
        }


        //右侧
        JSONArray value = algorithmParseObject.getObject("value", JSONArray.class);
        for (Object o : value) {
            JSONObject valObj = JSONObject.parseObject(JSON.toJSONString(o));
            String name = (String) valObj.get("time");
            paramList.add(name);
        }
        map.put("data", data);
        map.put("paramList", paramList);
        map.put("value", value);
        return map;
    }

    /**
     * 子任务 查看组装遥测数据
     *
     * @param paramSplit         参数代号
     * @param taskChildInfo      子任务对象
     * @param length             长度
     * @param type               类型
     * @param trailTelemetryList 手动试算遥测数据
     * @return Map<String, Object>
     */
    public Map<String, Object> assembleTelemetryListForKAndTwoAndFeature(String[] paramSplit, TaskChildInfo
            taskChildInfo, Integer length, String type, List<Map<String, Object>> trailTelemetryList) {
        HashMap<String, Object> finalMap = new HashMap<>(4);
        Map<String, Object> args = new LinkedHashMap<>();
        List<Map<String, Object>> telemetryList = new ArrayList<>();
        if (CollUtil.isNotEmpty(trailTelemetryList) && BeanUtil.isEmpty(taskChildInfo)) {
            telemetryList = trailTelemetryList;
        } else {
            for (String paramCode : paramSplit) {
                /*查询保存后的遥测数据*/
                TelemetryDto telemetryDto = new TelemetryDto();
                telemetryDto.setSatelliteCode(taskChildInfo.getSatelliteCode());
                telemetryDto.setParamCode(paramCode);
                telemetryDto.setStartTime(taskChildInfo.getStartTime());
                telemetryDto.setEndTime(taskChildInfo.getEndTime());
                List<TelemetryData> ycList = selectTelemetryDataSourceMapper.selectTelemetryListData(TableNameConstant.RUN_TASK_TELEMETRY + taskChildInfo.getId(),telemetryDto);
                /*原来查询遥测方式*/
//                Map<String, List<TelemetryData>> map = diagnoseService.selectTelemetryData(telemetryDto);
//                List<TelemetryData> ycList = map.get(paramCode);
                List<ArrayList<String>> collect = ycList.stream().map(x -> CollUtil.newArrayList(x.getTime(), x.getValue())).collect(Collectors.toList());
                args.put(paramCode, ycList);
                Map<String, Object> telemetry = new LinkedHashMap<>();
                telemetry.put("name", paramCode);
                telemetry.put("data", collect);
                telemetryList.add(telemetry);
            }
        }

        //获取到双参数遥测的最小长度
        if (StrUtil.isNotEmpty(type) && length == null && type.equals(MultiParameterEnum.TWOPARAMETERDIAGNOSISALGORITHM.getCode())) {
            ArrayList<Integer> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(telemetryList)) {
                for (Map<String, Object> map : telemetryList) {
                    ArrayList xlist = (ArrayList) map.get("data");
                    list.add(xlist.size());
                }
                Collections.sort(list);
                length = list.get(0);
            }
        }

        //x轴
        Set<Object> xAxis = new LinkedHashSet<>();
        //截图长度后的遥测
        List<Map<String, Object>> telemetryArrayList = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
        int j = 1;
        //排序拿到遥测长度的最小值，截取遥测长度一致，
        if (CollUtil.isNotEmpty(telemetryList) && length != null && StrUtil.isNotEmpty(type)) {
            for (String paramCode : paramSplit) {
                for (Map<String, Object> map : telemetryList) {
                    if (paramCode.equals(map.get("name"))) {
                        ArrayList dataList = (ArrayList) map.get("data");
                        HashMap<String, Object> telemetryMap = new HashMap<>(3);
                        telemetryMap.put("name", paramCode);
                        if (dataList.size() != length) {
                            ArrayList collect = (ArrayList) dataList.stream().limit(length).collect(Collectors.toList());
                            telemetryMap.put("data", collect);
                            telemetryArrayList.add(telemetryMap);
                            if (j == 1) {
                                for (Object o : collect) {
                                    List list1 = (List) o;
                                    xAxis.add(list1.get(0));
                                }
                                j++;
                            }
                        } else {
                            if (j == 1) {
                                for (Object o : dataList) {
                                    List list1 = (List) o;
                                    xAxis.add(list1.get(0));
                                }
                                j++;
                            }
                            telemetryMap.put("data", dataList);
                            telemetryArrayList.add(telemetryMap);
                        }

                    }
                }
            }
        }
        finalMap.put("xLineAxis", xAxis);
        finalMap.put("xAxis", xAxis);
        if (CollUtil.isNotEmpty(telemetryList) && length != null && StrUtil.isNotEmpty(type)) {
            telemetryArrayList=telemetryArrayList.stream()
                    .sorted(Comparator.comparing(m -> m.get("name").toString()))
                    .collect(Collectors.toList());
            finalMap.put("telemetryList", telemetryArrayList);
        } else {
            telemetryList=telemetryList.stream()
                    .sorted(Comparator.comparing(m -> m.get("name").toString()))
                    .collect(Collectors.toList());
            finalMap.put("telemetryList", telemetryList);
        }
        finalMap.put("args", args);
        return finalMap;
    }

    /**
     * 从事后诊断跳转获取趋势预测入参
     *
     * @param taskInfo           任务信息
     * @param errorParamCodeList 异常参数代号列表
     * @return Map<String, Object>
     */
    public Map<String, Object> getSearchKey(TaskInfo taskInfo, List<String> errorParamCodeList) {
        HashMap<String, Object> searchKeyMap = new HashMap<>(2);
        SatelliteCode satelliteCode = satelliteCodeService.selectOne(SatelliteCode.builder().satelliteCode(taskInfo.getSatelliteCode()).build());
        String[] paramCodeNameList = taskInfo.getParamCodeName().split(",");
        String[] paramCode = errorParamCodeList.get(0).split(",");
        String errorParamCodeName = "";
        String searchKey = "";
        if (ArrayUtil.isNotEmpty(paramCodeNameList) && BeanUtil.isNotEmpty(satelliteCode) && StrUtil.isNotEmpty(satelliteCode.getSatelliteName()) && ArrayUtil.isNotEmpty(paramCode)) {
            ArrayList<Object> list = new ArrayList<>();
            for (String codeName : paramCodeNameList) {
                for (String code : paramCode) {
                    if (codeName.contains(code)) {
                        list.add(codeName);
                    }
                }
            }
            searchKey = satelliteCode.getSatelliteName() + list.toString().replace("[", "").replace("]", "");
        } else if (ArrayUtil.isNotEmpty(paramCode)) {
            searchKey = satelliteCode.getSatelliteName();
        } else if (BeanUtil.isNotEmpty(satelliteCode) && StrUtil.isEmpty(satelliteCode.getSatelliteName())) {
            ArrayList<Object> list = new ArrayList<>();
            for (String codeName : paramCodeNameList) {
                for (String code : paramCode) {
                    if (codeName.contains(code)) {
                        list.add(codeName);
                    }
                }
            }
            searchKey = list.toString().replace("[", "").replace("]", "");
        }

        searchKeyMap.put("searchKey", searchKey);
        return searchKeyMap;
    }

    /**
     * 重组算法返回的anomaly和value值
     *
     * @param taskInfo 任务信息
     * @param taskId   任务id
     * @return Map<String, Object>
     */
    public Map<String, Object> assembleAnomalyAndValue(TaskInfo taskInfo, Long taskId) {
        SatelliteCode satelliteCode = satelliteCodeService.selectOne(SatelliteCode.builder().satelliteCode(taskInfo.getSatelliteCode()).build());
        HashMap<String, Object> finalMap = new HashMap<>(8);
        String[] split = taskInfo.getParams().split(",");
        List<MultiparatersDTO> getAnomalyList = faultInfoMapper.getAnomalyList(taskId);
        String data = "";
        ArrayList<String> tipsList = new ArrayList<>();
        if (CollUtil.isNotEmpty(getAnomalyList)) {
            Map<String, List<MultiparatersDTO>> anomalyMap = getAnomalyList.stream().collect(Collectors.groupingBy(MultiparatersDTO::getParamCode));
            Set<String> keySet = anomalyMap.keySet();
            for (String key : keySet) {
                tipsList.add(key);
            }
            data = "参数" + tipsList.toString().replace("[", "").replace("]", "") + "检测为异常！";
        }

        ArrayList<String> legend = new ArrayList<>();
        List<MultiparatersDTO> gradientMap = faultInfoMapper.getValueList(taskId);
        if (CollUtil.isNotEmpty(gradientMap)) {
            for (MultiparatersDTO valueDTO : gradientMap) {
                legend.add(valueDTO.getTime());
            }
        } else {
            gradientMap = new ArrayList<>();
            legend = new ArrayList<>();
        }
        String msg = "";
        String errorParamCode = "";
        List<MultiparatersDTO> msgList = faultInfoMapper.getMsgList(taskId);
        if (CollUtil.isNotEmpty(msgList)) {
            msg = msgList.get(0).getMsg();
            errorParamCode = msgList.get(0).getParamCode();
        }

        String[] paramCodeNameList = taskInfo.getParamCodeName().split(",");
        String errorParamCodeName = "";
        String searchKey = "";
        if (ArrayUtil.isNotEmpty(paramCodeNameList) && StrUtil.isNotEmpty(satelliteCode.getSatelliteName()) && CollUtil.isNotEmpty(tipsList)) {
            ArrayList<Object> list = new ArrayList<>();
            for (String code : paramCodeNameList) {
                for (String set : tipsList) {
                    if (code.contains(set)) {
                        list.add(code);
                    }
                }
            }
            searchKey = satelliteCode.getSatelliteName() + list.toString().replace("[", "").replace("]", "");
        } else if (CollUtil.isEmpty(tipsList)) {
            searchKey = satelliteCode.getSatelliteName();
        } else if (StrUtil.isEmpty(satelliteCode.getSatelliteName())) {
            ArrayList<Object> list = new ArrayList<>();
            for (String code : paramCodeNameList) {
                for (String set : tipsList) {
                    if (code.contains(set)) {
                        list.add(code);
                    }
                }
            }
            searchKey = list.toString().replace("[", "").replace("]", "");
        }


        //定死
        HashMap<String, Object> errorTimeMap = new HashMap<>(2);
        errorTimeMap.put("errorStartTime", "");
        errorTimeMap.put("errorEndTime", "");


        finalMap.put("errorTimeMap", errorTimeMap);
        finalMap.put("errorParamCode", errorParamCode);
        finalMap.put("msg", msg);
        finalMap.put("searchKey", searchKey);
        finalMap.put("legend", legend);
        finalMap.put("data", data);
        finalMap.put("gradientMap", gradientMap);
        return finalMap;
    }

}

